Skip to content

Instantly share code, notes, and snippets.

@alwarren
Created November 28, 2018 16:40
Show Gist options
  • Save alwarren/7d79c96d534e128763a8c1f673ce0e5d to your computer and use it in GitHub Desktop.
Save alwarren/7d79c96d534e128763a8c1f673ce0e5d to your computer and use it in GitHub Desktop.
Represent a square matrix using only List. Access to the matrix must use one-based indices.

Problem statement:

Represent a square matrix using only List. Access to the matrix must use one-based indices.

Given:

interface Cell {
    val i: Int
    val j: Int
}

interface SquareMatrix {
    val width: Int

    fun getCell(i: Int, j: Int): Cell
}

Implementation:

class Position(override val i: Int=0, override val j: Int=0) : Cell

Create the matrix

val width = 4
val list: List<Cell> by lazy {
	mutableListOf<Cell>().apply {
		(0 until width*width).forEach {
			val column = it % width
			val row = (it - column) / width
			add(Position(row + 1, column + 1))
		}
	}.toList()
}

Access the matrix:

override fun getCell(i: Int, j: Int): Cell {
	return list[(j - 1) + ((i - 1) * width)]
}

Example

println(matrix.getCell(1,1))

Output:

Position(i=1, j=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment