【发布时间】:2014-09-07 17:58:36
【问题描述】:
编辑:这最初是在programmers.stackexchange.com上,但由于我已经有一些代码,我认为这里可能会更好。
我正在尝试生成一个随机数学问题/方程式。在研究了我发现的最好的(也是唯一的)事情后,我发现了这个问题:Generating random math expression。因为我需要所有 4 个操作,而且我将在其中使用的应用程序是针对儿童的,所以我希望能够确保所有数字都是正数,除法是偶数等,我决定使用树.
我让这棵树工作,它可以生成一个等式并将其评估为一个数字。问题是我很难让它只在需要时使用括号。我尝试了几种解决方案,主要涉及:
- 查看这个节点是否在父节点的右边
- 查看节点是否比其父节点更重要/更不重要(* > + 等)。
- 查看节点及其父节点是否属于同一类型,如果是,则该操作的顺序是否重要。
没关系,我正在使用 Swift,这是我目前所拥有的:
func generateString(parent_node:TreeNode) -> String {
if(self.is_num){
return self.equation!
}
var equation = self.equation!
var left_equation : String = self.left_node!.generateString(self)
var right_equation : String = self.right_node!.generateString(self)
// Conditions for ()s
var needs_parentheses = false
needs_parentheses = parent_node.importance > self.importance
needs_parentheses = (
needs_parentheses
||
(
parent_node.right_node?.isEqualToNode(self)
&&
parent_node.importance <= self.importance
&&
(
parent_node.type != self.type
&&
( parent_node.order_matters != true || self.order_matters != true )
)
)
)
needs_parentheses = (
needs_parentheses
&&
(
!(
self.importance > parent_node.importance
)
)
)
if (needs_parentheses) {
equation = "(\(equation))"
}
return equation.stringByReplacingOccurrencesOfString("a", withString: left_equation).stringByReplacingOccurrencesOfString("b", withString: right_equation)
}
我无法让它工作,并且一直在用头撞墙。
我唯一能找到的关于删除括号的主题是:How to get rid of unnecessary parentheses in mathematical expression,我不知道如何将它应用到我的用例中。另外,我找到了this,我可能会尝试构建一个解析器(使用PEGKit),但我想知道是否有人有一个好主意来确定括号需要放在哪里,或者将它们放在任何地方并删除没用的。
编辑:为了清楚起见,我不需要有人为我写这个,我只是在寻找它需要做什么。
编辑 2: 由于这个应用程序将针对儿童,我希望尽可能少使用括号,同时保持等式正确。另外,上面的算法没有放足够的括号。
【问题讨论】:
-
你发现带有所有“悬挂括号”的缩进可读吗?
-
@GoZoner,我不确定你的意思。我能够阅读带有额外括号的方程式,但它的可读性不如我所希望的。另外,如果应用程序是针对儿童的,Simpler 会更好。另外,请参阅更新后的问题。
标签: math tree swift equation parentheses