Last active
November 29, 2017 01:08
-
-
Save cjnevin/9929cc02e4f785deb7b890fdc30ae82e to your computer and use it in GitHub Desktop.
FoldArray
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func fold(_ array: [Int], times: Int) -> [Int] { | |
let m = array.count / 2 | |
let middle = (array.count & 1 == 1 ? [array[m]] : []) | |
return times > 0 ? fold(zip(array.prefix(m), array.suffix(m).reversed()).map({ $0 + $1 }) + middle, times: times - 1) : array | |
} | |
fold([1,2,3,4,5], times: 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment