Day 8 revisited: Replaced manual prime factorization by new gcd and lcm toolset.

This commit is contained in:
Chris Hodges 2023-12-09 06:50:32 +01:00
parent f026dfb6de
commit 4c922f356d
2 changed files with 39 additions and 30 deletions

View File

@ -2,6 +2,13 @@ import java.io.File
import java.math.BigInteger
import java.security.MessageDigest
fun Int.gcd(b: Int): Int = if (b == 0) this else b.gcd(this % b)
fun Long.gcd(b: Long): Long = if (b == 0L) this else b.gcd(this % b)
fun Int.lcm(b: Int): Int = this / gcd(b) * b
fun Long.lcm(b: Long): Long = this / gcd(b) * b
fun Iterable<Int>.lcm(): Int = reduce(Int::lcm)
fun Iterable<Long>.lcm(): Long = reduce(Long::lcm)
/**
* Reads lines from the given input txt file.
*/

View File

@ -1,5 +1,6 @@
package aoc2023
import lcm
import println
import readInput
@ -95,36 +96,37 @@ XXX = (XXX, XXX)
} while (!loc.endsWith("Z"))
ggts.add(steps)
}
val primes = ArrayList<Int>()
val factors = HashSet<Int>()
var prime = 2
primes.add(2)
do {
val newGgts = HashSet<Int>()
for (f in ggts) {
if (prime * 2 - 1 > f) {
factors.add(f)
} else {
if (f % prime == 0) {
newGgts.add(f / prime)
factors.add(prime)
} else {
newGgts.add(f)
}
}
}
ggts = newGgts
if (prime == 2) {
prime = 3
} else {
do {
prime += 2
} while (primes.any { (prime % it) == 0 })
}
primes.add(prime)
} while (ggts.isNotEmpty())
return factors.map { it.toLong() }.reduce(Long::times)
return ggts.map(Int::toLong).lcm()
// val primes = ArrayList<Int>()
// val factors = HashSet<Int>()
// var prime = 2
// primes.add(2)
// do {
// val newGgts = HashSet<Int>()
// for (f in ggts) {
// if (prime * 2 - 1 > f) {
// factors.add(f)
// } else {
// if (f % prime == 0) {
// newGgts.add(f / prime)
// factors.add(prime)
// } else {
// newGgts.add(f)
// }
// }
// }
// ggts = newGgts
// if (prime == 2) {
// prime = 3
// } else {
// do {
// prime += 2
// } while (primes.any { (prime % it) == 0 })
// }
// primes.add(prime)
// } while (ggts.isNotEmpty())
//
// return factors.map { it.toLong() }.reduce(Long::times)
}
// test if implementation meets criteria from the description, like: