我尝试使用swift解析n级深度的多维数组。输入的一个例子是3级深度:
[+, 5, 4, ( "+", 4, ( "-", 7, 3 ) )]
代码的目标是将项目放在arr [0]并对该数组级别中的其他项执行该操作。
3嵌套for循环似乎是这个特定输入集的方法,但我无法弄清楚如何编写适用于n级深度数组的代码。
感谢。
答案 0 :(得分:0)
看起来你正在构建一个RPN计算器。您可以使用递归代替嵌套if
:
func evaluate (stack: [AnyObject]) -> Double {
func apply(op: String, _ operand1: Double, _ operand2: Double) -> Double {
switch op {
case "+": return operand1 + operand2
case "-": return operand1 - operand2
case "x": return operand1 * operand2
case "/": return operand1 / operand2
default:
print("Invalid operator: \(op)")
return Double.NaN
}
}
guard let op = stack[0] as? String else {
fatalError("stack must begin with an operator")
}
switch (stack[1], stack[2]) {
case (let operand1 as [AnyObject], let operand2 as [AnyObject]):
return apply(op, evaluate(operand1), evaluate(operand2))
case (let operand1 as [AnyObject], let operand2 as Double):
return apply(op, evaluate(operand1), operand2)
case (let operand1 as Double, let operand2 as [AnyObject]):
return apply(op, operand1, evaluate(operand2))
case (let operand1 as Double, let operand2 as Double):
return apply(op, operand1, operand2)
default:
print("I don't know how to handle this: \(stack)")
return Double.NaN
}
}
let rpnStack = ["+", 5, ["+", 4, [ "-", 7, 3]]]
let result = evaluate(rpnStack)
print(result) // 13
这显然假设每个级别的表达式树包含完全3个节点。