Day 8 revisited: Replaced manual prime factorization by new gcd and lcm toolset.
This commit is contained in:
parent
f026dfb6de
commit
4c922f356d
@ -2,6 +2,13 @@ import java.io.File
|
|||||||
import java.math.BigInteger
|
import java.math.BigInteger
|
||||||
import java.security.MessageDigest
|
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.
|
* Reads lines from the given input txt file.
|
||||||
*/
|
*/
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
package aoc2023
|
package aoc2023
|
||||||
|
|
||||||
|
import lcm
|
||||||
import println
|
import println
|
||||||
import readInput
|
import readInput
|
||||||
|
|
||||||
@ -95,36 +96,37 @@ XXX = (XXX, XXX)
|
|||||||
} while (!loc.endsWith("Z"))
|
} while (!loc.endsWith("Z"))
|
||||||
ggts.add(steps)
|
ggts.add(steps)
|
||||||
}
|
}
|
||||||
val primes = ArrayList<Int>()
|
return ggts.map(Int::toLong).lcm()
|
||||||
val factors = HashSet<Int>()
|
// val primes = ArrayList<Int>()
|
||||||
var prime = 2
|
// val factors = HashSet<Int>()
|
||||||
primes.add(2)
|
// var prime = 2
|
||||||
do {
|
// primes.add(2)
|
||||||
val newGgts = HashSet<Int>()
|
// do {
|
||||||
for (f in ggts) {
|
// val newGgts = HashSet<Int>()
|
||||||
if (prime * 2 - 1 > f) {
|
// for (f in ggts) {
|
||||||
factors.add(f)
|
// if (prime * 2 - 1 > f) {
|
||||||
} else {
|
// factors.add(f)
|
||||||
if (f % prime == 0) {
|
// } else {
|
||||||
newGgts.add(f / prime)
|
// if (f % prime == 0) {
|
||||||
factors.add(prime)
|
// newGgts.add(f / prime)
|
||||||
} else {
|
// factors.add(prime)
|
||||||
newGgts.add(f)
|
// } else {
|
||||||
}
|
// newGgts.add(f)
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
ggts = newGgts
|
// }
|
||||||
if (prime == 2) {
|
// ggts = newGgts
|
||||||
prime = 3
|
// if (prime == 2) {
|
||||||
} else {
|
// prime = 3
|
||||||
do {
|
// } else {
|
||||||
prime += 2
|
// do {
|
||||||
} while (primes.any { (prime % it) == 0 })
|
// prime += 2
|
||||||
}
|
// } while (primes.any { (prime % it) == 0 })
|
||||||
primes.add(prime)
|
// }
|
||||||
} while (ggts.isNotEmpty())
|
// primes.add(prime)
|
||||||
|
// } while (ggts.isNotEmpty())
|
||||||
return factors.map { it.toLong() }.reduce(Long::times)
|
//
|
||||||
|
// return factors.map { it.toLong() }.reduce(Long::times)
|
||||||
}
|
}
|
||||||
|
|
||||||
// test if implementation meets criteria from the description, like:
|
// test if implementation meets criteria from the description, like:
|
||||||
|
Loading…
Reference in New Issue
Block a user