Created
June 10, 2021 19:34
-
-
Save jakebromberg/4ed195b078ecbf9da9b3884a5513115a to your computer and use it in GitHub Desktop.
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
struct Matrix<Element> { | |
private var storage: [[Element]] | |
init(_ storage: [[Element]]) { | |
self.storage = storage | |
} | |
} | |
extension Matrix: Collection { | |
struct Index: Comparable { | |
static func < (lhs: Matrix<Element>.Index, rhs: Matrix<Element>.Index) -> Bool { | |
return lhs.x < rhs.x && lhs.y < rhs.y | |
} | |
let x: Int | |
let y: Int | |
} | |
func index(after i: Index) -> Index { | |
if (i.x == storage.count - 1) { | |
return Index(x: 0, y: i.y + 1) | |
} else { | |
return Index(x: i.x + 1, y: i.y) | |
} | |
} | |
subscript(position: Index) -> Element { | |
get { | |
storage[position.y][position.x] | |
} | |
set { | |
storage[position.y][position.x] = newValue | |
} | |
} | |
var startIndex: Index { | |
Index(x: 0, y: 0) | |
} | |
var endIndex: Index { | |
Index(x: 0, y: storage[0].count) | |
} | |
} | |
let m = Matrix([ | |
[0, 1], | |
[2, 3] | |
]) | |
for e in m { | |
print(e) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment