Created
December 4, 2021 10:25
-
-
Save rayalex/0c398937aa84d9e1bc6bcf40d1d388ea to your computer and use it in GitHub Desktop.
Kotlin 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
| class Matrix<T>(val width: Int, val height: Int, init: () -> T) : Iterable<T> { | |
| private val data = List(width) { MutableList(height) { init() } } | |
| fun dimension() = width * height | |
| fun get(x: Int, y: Int): T = data[x][y] | |
| fun set(value: T, x: Int, y: Int) { | |
| data[x][y] = value | |
| } | |
| override fun iterator(): Iterator<T> { | |
| return MatrixIterator(this) | |
| } | |
| } | |
| class MatrixIterator<T>(private val matrix: Matrix<T>) : Iterator<T> { | |
| private val max = matrix.dimension() | |
| private var current = 0 | |
| override fun hasNext(): Boolean { | |
| return current < max | |
| } | |
| override fun next(): T { | |
| val (x, y) = rowWiseSequenceToCoordinate(current) | |
| current += 1 | |
| return matrix.get(x, y) | |
| } | |
| private fun rowWiseSequenceToCoordinate(sequence: Int): Pair<Int, Int> { | |
| val row = (sequence) % (matrix.width) | |
| val col = (sequence) / (matrix.width) | |
| return Pair(row, col) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment