Skip to content

Commit aee3836

Browse files
committed
code refactoring
1 parent 6b70ba1 commit aee3836

File tree

2 files changed

+29
-3
lines changed
  • src/main/kotlin/tr/emreone/kotlin_utils

2 files changed

+29
-3
lines changed

src/main/kotlin/tr/emreone/kotlin_utils/automation/Day.kt

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,7 @@ open class Day private constructor(
1515
title: String = "Puzzle unknown",
1616
terminal: Terminal = aocTerminal,
1717
session: String? = null
18-
) : this(
19-
AoCPuzzle(day, year), title, terminal, AdventOfCode(session)
20-
)
18+
) : this(AoCPuzzle(day, year), title, terminal, AdventOfCode(session))
2119

2220
var testInput = false
2321

src/main/kotlin/tr/emreone/kotlin_utils/math/Math.kt

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,34 @@ fun lcm(a: Long, b: Long) = (a safeTimes b) / gcd(a, b)
3333
fun lcm(f: Long, vararg n: Long): Long = n.fold(f, ::lcm)
3434
fun Iterable<Long>.lcm(): Long = reduce(::lcm)
3535

36+
37+
/**
38+
* Takes a list of base/modulo combinations and returns the lowest number for which the states coincide such that:
39+
*
40+
* for all i: state(i) == base_state(i).
41+
*
42+
* E.g. chineseRemainder((3,4), (5,6), (2,5)) == 47
43+
*/
44+
fun chineseRemainder(values: List<Pair<Long, Long>>): Pair<Long, Long>? {
45+
if (values.isEmpty()) {
46+
return null
47+
}
48+
var (result, lcm) = values[0]
49+
outer@ for (i in 1 until values.size) {
50+
val (base, modulo) = values[i]
51+
val target = base % modulo
52+
for (j in 0L until modulo) {
53+
if (result % modulo == target) {
54+
lcm = lcm(lcm, modulo)
55+
continue@outer
56+
}
57+
result += lcm
58+
}
59+
return null
60+
}
61+
return result to lcm
62+
}
63+
3664
/**
3765
* Simple algorithm to find the primes of the given Int.
3866
*/

0 commit comments

Comments
 (0)