-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day25.kt
73 lines (60 loc) · 1.55 KB
/
Day25.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package aoc.years.year2022
import aoc.Day
import kotlin.math.pow
@Year2022
class Day25 : Day() {
override fun solvePart1(input: List<String>): Any {
return input.sumOf { it.toDecimal() }.toSnafu()
}
override fun solvePart2(input: List<String>): Any {
return "Merry Christmas 🎅"
}
}
private fun String.toDecimal(): Long {
return toList()
.reversed()
.mapIndexed { index, char ->
val times = when (char) {
'-' -> -1
'=' -> -2
else -> char.digitToInt()
}
return@mapIndexed 5.0.pow(index) * times
}
.sum()
.toLong()
}
fun Long.toSnafu(): String {
val base5Number = mutableListOf<Int>()
// First convert to "normal" base5 number
var quotient = this
do {
val rem = quotient.rem(5)
quotient = quotient.div(5)
base5Number.add(rem.toInt())
} while (quotient != 0L)
// Then convert any 3's and 4's
val snafu = StringBuilder()
var carrier = 0
for (digit in base5Number) {
when (val newDigit = digit + carrier) {
5 -> {
snafu.append("0")
carrier = 1
}
4 -> {
snafu.append("-")
carrier = 1
}
3 -> {
snafu.append("=")
carrier = 1
}
else -> {
snafu.append(newDigit)
carrier = 0
}
}
}
return snafu.reversed().toString()
}