2016-06-07 65 views
0

我想使用swift解析n维深度的多维数组。输入的一个例子,即3个层次深,是:在swift中解析n维数组

[+, 5, 4, ("+", 4, ("-", 7, 3))] 

代码的目标是采取了该项目ARR [0]和做在所述阵列的那级别的操作,以其他项目。

3嵌套for循环似乎是这种特定输入集合的方式,但我无法弄清楚如何编写适用于n级深度数组的代码。

谢谢。

+3

昨天你不是问这个问题吗? – NRitH

回答

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个节点。