Created
December 2, 2015 04:34
-
-
Save danielpi/a64e9198a828080abe84 to your computer and use it in GitHub Desktop.
Turn a list into a matrix
This file contains hidden or 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
//: # 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