我正在尝试使用 swift 解析一个 n 层深的多维数组。 3 级深度的输入示例是:
[+, 5, 4, ( "+", 4, ( "-", 7, 3 ) )]
代码的目标是获取 arr[0] 处的项目并对数组该级别中的其他项目执行该操作。
3 嵌套 for 循环似乎是处理这个特定输入集的方法,但我不知道如何编写适用于 n 层深度的数组的代码。
谢谢。
最佳答案
看起来您正在构建一个 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 个节点。
关于arrays - 快速解析一个n维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37669154/