This commit is contained in:
alex-s168
2024-03-29 20:02:20 +01:00
parent b8bd109182
commit 8db5ca9171
3 changed files with 86 additions and 1 deletions

View File

@@ -5,7 +5,7 @@ plugins {
}
group = "me.alex_s168"
version = "0.10"
version = "0.11"
repositories {
mavenCentral()

View File

@@ -0,0 +1,15 @@
package blitz.collections
/** Returns the element that is at all positions in the list (if there is one) */
fun <T> Iterable<T>.findCommon(): T? =
firstOrNull()?.let { first ->
if (all { it == first }) first
else null
}
/** Returns the element that is at all positions in the list (if there is one) */
fun <T> Sequence<T>.findCommon(): T? =
firstOrNull()?.let { first ->
if (all { it == first }) first
else null
}

View File

@@ -0,0 +1,70 @@
package blitz.collections
import kotlin.math.min
class Matrix<T>(
val width: Int,
val height: Int,
private val init: (x: Int, y: Int) -> T
) {
val rows = MutableList(height) { y ->
MutableList(width) { x ->
init(x, y)
}
}
operator fun get(x: Int, y: Int): T =
rows[y][x]
operator fun set(x: Int, y: Int, value: T) {
rows[y][x] = value
}
fun transposeCopy(): Matrix<T> =
Matrix(width, height) { x, y -> this[y, x] }
fun perfectSquareCopy(): Matrix<T> =
min(width, height).let { wh ->
Matrix(wh, wh) { x, y -> this[x, y] }
}
fun copy(): Matrix<T> =
Matrix(width, height) { x, y -> this[x, y] }
fun diagonalTopLeftToBottomRight(to: MutableList<T> = mutableListOf()): MutableList<T> {
repeat(min(width, height)) { pos ->
to.add(this[pos, pos])
}
return to
}
fun diagonalTopRightToBottomLeft(to: MutableList<T> = mutableListOf()): MutableList<T> {
val wh = min(width, height)
for(pos in wh - 1 downTo 0) {
to.add(this[pos, wh - 1 - pos])
}
return to
}
fun diagonals(to: MutableList<MutableList<T>> = mutableListOf()): MutableList<MutableList<T>> {
to.add(diagonalTopLeftToBottomRight())
to.add(diagonalTopRightToBottomLeft())
return to
}
// TODO: make better
override fun toString(): String =
"--\n" +
rows.joinToString(separator = "\n") {
it.joinToString(separator = ", ", prefix = "| ", postfix = " |")
} + "\n--"
}
fun main() {
val mat = Matrix(3, 3) { x, y -> x * (3-y) }
println(mat)
println(mat.transposeCopy())
println(mat.diagonals())
}