Skip to content

Commit d40f539

Browse files
committed
Simplify integer Gaussian elimination in 2025 day 10 part 2
1 parent 3950130 commit d40f539

File tree

1 file changed

+22
-28
lines changed

1 file changed

+22
-28
lines changed

src/main/scala/eu/sim642/adventofcode2025/Day10.scala

Lines changed: 22 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -136,25 +136,28 @@ object Day10 {
136136

137137
def multiplyRow(y: Int, factor: Long): Unit = {
138138
for (x2 <- 0 until (machine.buttons.size + 1))
139-
m(y)(x2) *= factor.toLong
139+
m(y)(x2) *= factor
140140
}
141141

142-
def reduceDown(x: Int, y1: Int, y2: Int): Unit = {
143-
val c1 = m(y1)(x)
144-
assert(c1 > 0)
145-
val c2 = m(y2)(x)
146-
val cd = NumberTheory.lcm(c1, c2.abs)
147-
multiplyRow(y1, cd / c1)
148-
multiplyRow(y2, cd / c2)
149-
val factor = m(y2)(x) / m(y1)(x)
150-
for (x2 <- x until (machine.buttons.size + 1))
151-
m(y2)(x2) -= factor * m(y1)(x2)
142+
def simplifyRow(y: Int): Unit = {
143+
val factor = NumberTheory.gcd(m(y).toSeq) // TODO: avoid conversion
144+
if (factor.abs > 1) {
145+
for (x2 <- 0 until (machine.buttons.size + 1))
146+
m(y)(x2) /= factor
147+
}
152148
}
153149

154-
def reduceUp(x: Int, y1: Int, y2: Int): Unit = {
155-
val factor = m(y2)(x) / m(y1)(x)
156-
for (x2 <- 0 until (machine.buttons.size + 1)) // TODO: enough to also start from x? (before zeros anyway)
157-
m(y2)(x2) -= factor * m(y1)(x2)
150+
def reduceDown(x: Int, y1: Int, y2: Int): Unit = {
151+
val c2 = m(y2)(x)
152+
if (c2 != 0) {
153+
val c1 = m(y1)(x)
154+
val (_, _, (factor, factor2)) = NumberTheory.extendedGcd(c1, c2)
155+
for (x2 <- 0 until x) // must start from 0 because we're now multiplying entire row y2
156+
m(y2)(x2) = factor2 * m(y2)(x2)
157+
for (x2 <- x until (machine.buttons.size + 1))
158+
m(y2)(x2) = factor2 * m(y2)(x2) + factor * m(y1)(x2)
159+
//simplifyRow(y2)
160+
}
158161
}
159162

160163
var y = 0
@@ -164,13 +167,8 @@ object Day10 {
164167
case None => // move to next x
165168
case Some(y2) =>
166169
swapRows(y, y2)
167-
multiplyRow(y, m(y)(x).sign) // make leading coeff positive
168-
//assert(m(y)(x).abs == 1) // TODO: this will probably change
169-
170-
for (y3 <- (y + 1) until m.size) {
171-
if (m(y3)(x) != 0)
172-
reduceDown(x, y, y3)
173-
}
170+
for (y3 <- (y + 1) until m.size)
171+
reduceDown(x, y, y3)
174172

175173
y += 1
176174
}
@@ -191,12 +189,8 @@ object Day10 {
191189
} // move to next x
192190
else {
193191
mainVars += x
194-
multiplyRow(y, m(y)(x).sign) // make leading coeff positive
195-
for (y3 <- 0 until y) {
196-
if (m(y3)(x) != 0)
197-
//reduceUp(x, y, y3)
198-
reduceDown(x, y, y3)
199-
}
192+
for (y3 <- 0 until y)
193+
reduceDown(x, y, y3)
200194

201195
y += 1
202196
}

0 commit comments

Comments
 (0)