簡體   English   中英

快速解析n維數組

[英]Parsing a n-dimensional array in swift

我正在嘗試使用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個節點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM