Skip to content

Instantly share code, notes, and snippets.

@sczerwinski
Last active July 4, 2017 18:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sczerwinski/3d98549ebb8c48f7b4b38e898e30fb30 to your computer and use it in GitHub Desktop.
Save sczerwinski/3d98549ebb8c48f7b4b38e898e30fb30 to your computer and use it in GitHub Desktop.
Functional square matrix
package pl.info.czerwinski.geom
class SquareMatrix(val size: Int, private val elements: (Int, Int) -> Float) {
operator fun get(row: Int, col: Int): Float {
require(row in 0..size - 1) { "Row ${row} out of bounds: 0..${size - 1}" }
require(col in 0..size - 1) { "Column ${col} out of bounds: 0..${size - 1}" }
return elements(row, col)
}
val det: Float by lazy {
if (size == 1) this[0, 0]
else (0..size - 1).map { item -> this[0, item] * comatrix[0, item] }.sum()
}
private val comatrix: SquareMatrix by lazy {
SquareMatrix(size) { row, col -> cofactor(row, col) }
}
private fun cofactor(row: Int, col: Int): Float =
minor(row, col) * if ((row + col) % 2 == 0) 1f else -1f
private fun minor(row: Int, col: Int): Float =
sub(row, col).det
private fun sub(delRow: Int, delCol: Int) = SquareMatrix(size - 1) { row, col ->
this[if (row < delRow) row else row + 1, if (col < delCol) col else col + 1]
}
val adj: SquareMatrix by lazy { comatrix.transpose() }
fun transpose(): SquareMatrix = SquareMatrix(size) { row, col -> this[col, row] }
fun inverse(): SquareMatrix = SquareMatrix(size) { row, col -> adj[row, col] / det }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment