Skip to content

Instantly share code, notes, and snippets.

@cjnevin
Last active November 29, 2017 01:08
Show Gist options
  • Save cjnevin/9929cc02e4f785deb7b890fdc30ae82e to your computer and use it in GitHub Desktop.
Save cjnevin/9929cc02e4f785deb7b890fdc30ae82e to your computer and use it in GitHub Desktop.
FoldArray
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