Skip to content

Instantly share code, notes, and snippets.

@rayalex
Created December 4, 2021 10:25
Show Gist options
  • Select an option

  • Save rayalex/0c398937aa84d9e1bc6bcf40d1d388ea to your computer and use it in GitHub Desktop.

Select an option

Save rayalex/0c398937aa84d9e1bc6bcf40d1d388ea to your computer and use it in GitHub Desktop.
Kotlin Matrix
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