在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)]
    }
}

解决方法

如果您使用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")]
,

希望这使您更容易理解。

var count = Object.keys(adresss).length
console.log('count'+count); // it gives 4 which is character lenght,but I want 1,Because of this I can't update the array of addresses. How can I get this