diff --git a/src/Utils.kt b/src/Utils.kt index 14568d2..49e1893 100644 --- a/src/Utils.kt +++ b/src/Utils.kt @@ -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.lcm(): Int = reduce(Int::lcm) +fun Iterable.lcm(): Long = reduce(Long::lcm) + /** * Reads lines from the given input txt file. */ diff --git a/src/aoc2023/Day08.kt b/src/aoc2023/Day08.kt index 633f5fc..6bba147 100644 --- a/src/aoc2023/Day08.kt +++ b/src/aoc2023/Day08.kt @@ -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() - val factors = HashSet() - var prime = 2 - primes.add(2) - do { - val newGgts = HashSet() - 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() +// val factors = HashSet() +// var prime = 2 +// primes.add(2) +// do { +// val newGgts = HashSet() +// 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: