首页 » Swift » 趣味编程:静夜思(Swift版)

趣味编程:静夜思(Swift版)

原文 http://blog.csdn.net/zwvista/article/details/76551250

2017-08-01 20:20:08阅读(589)

// https://stackoverflow.com/questions/31220002/how-to-group-by-the-elements-of-an-array-in-Swift
extension Sequence {
    func group<GroupingType: Hashable>(by key: (Iterator.Element) -> GroupingType) -> [[Iterator.Element]] {
        var groups: [GroupingType: [Iterator.Element]] = [:]
        var groupsOrder: [GroupingType] = []
        forEach { element in
            let key = key(element)
            if case nil = groups[key]?.append(element) {
                groups[key] = [element]
                groupsOrder.append(key)
            }
        }
        return groupsOrder.map { groups[$0]! }
    }
}
func verticalWriting(txt:String, offset:Int) {
    txt.characters.enumerated()
        .group(by: {(i, c) in i % offset})
        .forEach{print(
            $0.map({String($0.element)}).reversed().joined(separator: "|")
        )}
}
verticalWriting(txt: "床前明月光疑是地上霜举头望明月低头思故乡", offset: 5)
/*
低|举|疑|床
头|头|是|前
思|望|地|明
故|明|上|月
乡|月|霜|光
*/

最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹