arrays - 快速解析一个n维数组

标签 arrays swift multidimensional-array

我正在尝试使用 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/

相关文章:

c++ - 我正在尝试设置几个不同的多维数组,但无法弄清楚为什么这不起作用

javascript - 合并数组内多个对象的值

swift - 如何向 CollectionView 单元格内的图像添加渐变层

c - 反转数组的函数 - C

swift - 播放下载到缓存目录的歌曲

ios - 来自可重复使用的表格单元格的不同 segues

arrays - 在 Golang 中创建哈希数组

C++ 多维数组和指针名称括号

c# - 以最佳方式检查算术字符串括号对称性

javascript - 如何在许多已排序的数字数组中找到一个数字?