I'm trying to parse a multidimensional array that is n levels deep using swift. An example of the input, that is 3 levels deep, is:
[+, 5, 4, ( "+", 4, ( "-", 7, 3 ) )]
The goal of the code is to take the item at arr[0] and do that operation to the other items in that level of the array.
3 nested for loops seems like the way to go for this particular input set, but I can't figure out how to write code that will work for arrays that are n levels deep.
Thanks.
Look like you are building an RPN calculator. Instead of nested if
, you can use recursion:
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
This obviously assumes the expression tree at each level contains exact 3 nodes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.