From 877a6f51e37f99a272c9e70e724ae2e80b6e28c5 Mon Sep 17 00:00:00 2001 From: alex-s168 <63254202+alex-s168@users.noreply.github.com> Date: Wed, 12 Jun 2024 22:19:55 +0200 Subject: [PATCH] v0.16: matrix stuff --- README.md | 2 +- build.gradle.kts | 2 +- src/main/kotlin/blitz/collections/Matrix.kt | 40 ++++++++++++++++----- 3 files changed, 33 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index f884c4a..b0f3afe 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ repositories { } dependencies { - implementation("me.alex_s168:blitz:0.15") + implementation("me.alex_s168:blitz:0.16") } ``` diff --git a/build.gradle.kts b/build.gradle.kts index 1290dbb..c8b820c 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -5,7 +5,7 @@ plugins { } group = "me.alex_s168" -version = "0.15" +version = "0.16" repositories { mavenCentral() diff --git a/src/main/kotlin/blitz/collections/Matrix.kt b/src/main/kotlin/blitz/collections/Matrix.kt index d0cc4e1..8de2550 100644 --- a/src/main/kotlin/blitz/collections/Matrix.kt +++ b/src/main/kotlin/blitz/collections/Matrix.kt @@ -1,5 +1,6 @@ package blitz.collections +import blitz.str.MutMultiLineString import kotlin.math.min class Matrix( @@ -27,9 +28,23 @@ class Matrix( rows[pos.second][pos.first] = value } + fun row(row: Int): IndexableSequence = + rows[row].asSequence().asIndexable() + fun column(col: Int): IndexableSequence = generateSequenceWithIndex(height) { row -> this[col, row] } + fun elements(): Sequence = + rows.asSequence().flatten() + + fun elementsWithIndexes(): Sequence>> = + rows.asSequence() + .flatMapIndexed { row, ts -> + ts.mapIndexed { col, t -> + t to (col to row) + } + } + fun fill(fn: (x: Int, y: Int) -> T) { repeat(height) { row -> repeat(width) { col -> @@ -95,19 +110,23 @@ class Matrix( fun toString(alignRight: Boolean): String { val str = stringMat() + val widths = str.columnWidths() - val out = StringBuilder() + val heights = str.rowHeights() - val padfn = if (alignRight) String::padStart else String::padEnd + val out = MutMultiLineString(' ') + var y = 0 str.rows.forEachIndexed { row, elems -> - if (row > 0) - out.append('\n') - elems.forEachIndexed { col, x -> - if (col > 0) - out.append(' ') - out.append(padfn(x, widths[col], ' ')) + var x = 0 + elems.forEachIndexed { col, elem -> + if (alignRight) + out[y, x + widths[col] - elem.lines().maxOf { it.length }] = MutMultiLineString.from(elem, ' ') + else + out[y, x] = elem + x += widths[col] + 1 } + y += heights[row] + 1 } return out.toString() @@ -124,7 +143,10 @@ class Matrix( } fun Matrix.columnWidths(): IntArray = - IntArray(width) { col -> column(col).maxOf { it.length } } + IntArray(width) { col -> column(col).maxOf { it.lines().maxOf { it.length } } } + +fun Matrix.rowHeights(): IntArray = + IntArray(height) { row -> row(row).maxOf { it.lines().size } } fun Matrix.lengths(): Matrix = Matrix(width, height) { x, y -> this[x, y].length }