【问题标题】:Any easier to read run-length Encoding in Swift?Swift 中的游程编码更容易阅读吗?
【发布时间】:2020-08-16 13:35:13
【问题描述】:

任何人都可以用 swift 编写比下面更容易阅读的运行长度编码代码,或者至少解释一下我从 rosettecode.org 获得的代码吗? 这是输入输出和代码

// "WWWBWW" -> [(3, W), (1, B), (2, W)]

func encode(input: String) -> [(Int, Character)] {
    return input.characters.reduce([(Int, Character)]()) {
        if $0.last?.1 == $1 { var r = $0; r[r.count - 1].0++; return r }
        return $0 + [(1, $1)]
    }
}

【问题讨论】:

  • 那是相当糟糕的代码,不要用作参考。非常适合打代码高尔夫,完全是为了解决一个简单的问题而写的令人麻木的复杂。再加上它很旧,前缀和后缀递增/递减运算符(++--)已在一段时间前从 Swift 中删除。

标签: swift run-length-encoding


【解决方案1】:

如果你改用reduce(into:)会更容易理解:

func encode(input: String) -> [(Int, Character)] {
    input.reduce(into: [(Int, Character)]()) {
        // if the second element of the last tuple of the result is equal to the current element (character) of the collection
        if $0.last?.1 == $1 {
            // increase the first element of the last tuple tuple of the result
            $0[$0.index(before: $0.endIndex)].0 += 1 
        } else {
            // otherwise add a new tuple with a value of 1 and the current element (character) to the result
            $0 += CollectionOfOne((1, $1))
        }
    }
}

encode(input: "WWWBWW")  // [(.0 3, .1 "W"), (.0 1, .1 "B"), (.0 2, .1 "W")]

您还可以扩展 Collection 并实现通用方法/属性

extension Collection where Element: Equatable {
    var groupped: [(Int, Element)] {
        reduce(into: []) {
            if $0.last?.1 == $1 {
                $0[$0.index(before: $0.endIndex)].0 += 1
            } else {
                $0 += CollectionOfOne((1, $1))
            }
        }
    }
}

"WWWBWW".groupped    // [(.0 3, .1 "W"), (.0 1, .1 "B"), (.0 2, .1 "W")]

【讨论】:

    【解决方案2】:

    希望这能让你更容易理解。

    func encode2(input: String) -> [(Int, Character)] {
        var result = [(Int, Character)]()
    
        input.forEach { char in
            if result.last?.1 == char {
                result[result.count - 1].0 += 1
            } else {
                result.append((1, char))
            }
        }
        
        return result
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-06
      • 1970-01-01
      • 2020-10-19
      • 2011-12-04
      • 2014-07-10
      • 1970-01-01
      • 2019-08-12
      相关资源
      最近更新 更多