Skip to content

Instantly share code, notes, and snippets.

@danielpi
Created December 2, 2015 04:34
Show Gist options
  • Save danielpi/a64e9198a828080abe84 to your computer and use it in GitHub Desktop.
Save danielpi/a64e9198a828080abe84 to your computer and use it in GitHub Desktop.
Turn a list into a matrix
//: # Matrify
//:
//: Turn a list into a matrix
import Cocoa
let a = [1,2,3,4,5,6,7,8,9]
func matrify(list: [Int], rowLength: Int) -> [[Int]] {
func iter(list: [Int], matrix: [[Int]]) -> [[Int]] {
if list.count < rowLength {
return matrix + [list]
} else {
return iter(Array(list[rowLength..<list.count]), matrix: matrix + [Array(list[0..<rowLength])])
}
}
return iter(list, matrix: [])
}
matrify(a, rowLength: 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment