2016-06-07 77 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個節點。