如何解决在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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。