Use substring iterator directly

This commit is contained in:
Sven Weidauer 2024-12-07 13:10:21 +01:00
parent e1f0159403
commit 6f7fc2d1a8

View file

@ -13,23 +13,21 @@ class Grid(val rows: List<String>) {
fun chars(x: Int, y: Int, dx: Int, dy: Int) = Line(x, y, dx, dy) fun chars(x: Int, y: Int, dx: Int, dy: Int) = Line(x, y, dx, dy)
inner class Line(val x: Int, val y: Int, val dx: Int, val dy: Int) : Sequence<Char> { inner class Line(val x: Int, val y: Int, val dx: Int, val dy: Int) : Sequence<Char> {
override fun iterator(): Iterator<Char> = iterator { override fun iterator(): Iterator<Char> = if (dx == 1 && dy == 0) {
if (dx == 1 && dy == 0) { rows[y].substring(startIndex = x).iterator()
yieldAll(rows[y].substring(startIndex = x).asSequence()) } else iterator {
} else { var x = x
var y = y
var x = x while (x in 0..<width && y in 0..<height) {
var y = y yield(get(x, y))
x += dx
while (x in 0..<width && y in 0..<height) { y += dy
yield(get(x, y))
x += dx
y += dy
}
} }
} }
} }
fun rows(): Sequence<Line> = sequence { fun rows(): Sequence<Line> = sequence {
for (y in 0..<height) { for (y in 0..<height) {
yield(chars(0, y, 1, 0)) yield(chars(0, y, 1, 0))