Advent of Code 2021 day 25
12/25/2022, 5:00 AMDavid Whittaker
12/25/2022, 5:34 AMKroppeb
12/25/2022, 5:35 AMCognitive Gear
12/25/2022, 5:44 AMSergei Petunin
12/25/2022, 5:48 AMtoSnafu()
converter works well for all numbers in the example, but doesn't work for the inputSergei Petunin
12/25/2022, 5:51 AMCognitive Gear
12/25/2022, 5:53 AMSergei Petunin
12/25/2022, 6:13 AMtoSnafu()
, that was fromSnafu()
giving me wrong results because of int overflow... 🤦♂️Jakub Gwóźdź
12/25/2022, 6:13 AMfun part1(input: String) = input.lineSequence()
.sumOf(::decode)
.let(::encode)
private const val DIGITS = "=-012"
private fun decode(line: String) = line.fold(0L) { acc, c ->
acc * 5 + DIGITS.indexOf(c) - 2
}
But I wonder if there’s a way to oneline encoding using kotlin’s stdlib goodies.
so far mine looks like this:
private fun encode(number: Long): String {
if (number == 0L) return "0"
var b = number
return buildString {
while (b > 0) {
val m = (b + 2) % 5
b = (b + 2) / 5
append(DIGITS[m.toInt()])
}
}.reversed()
}
Sergei Petunin
12/25/2022, 6:40 AMfun Long.toSnafu() = generateSequence(this to "") { (number, acc) ->
val remainder = number.mod(5)
(number + 5 * (remainder / 3)) / 5 to "012=-"[remainder] + acc
}.first { it.first == 0L }.second
Sergei Petunin
12/25/2022, 6:47 AMJonathan Kolberg
12/25/2022, 7:11 AMJonathan Kolberg
12/25/2022, 7:29 AMMarcin Wisniowski
12/25/2022, 8:43 AM5f.pow(19).toLong()
gives the wrong result. 😢Marcin Wisniowski
12/25/2022, 8:44 AMOzioma Ogbe
12/25/2022, 9:41 AMOzioma Ogbe
12/25/2022, 9:45 AMAdam S
12/25/2022, 10:24 AMSergei Petunin
12/25/2022, 11:58 AMclass Day25(val contents: String) {
private val digits = "=-012"
fun part1() = contents.lines().fold("0") { acc, line ->
val maxLen = max(line.length, acc.length) + 1
acc.padStart(maxLen, '0').zip(line.padStart(maxLen, '0'))
.foldRight("" to 0) { (a, b), (result, carry) ->
val sum = digits.indexOf(a) + digits.indexOf(b) - 4 + carry
(digits[(sum + 7) % 5] + result) to sum / 3
}.first.trimStart('0')
}
}
ephemient
12/25/2022, 12:00 PMephemient
12/25/2022, 12:13 PMgenerateSequence
instead of a loopritesh
12/25/2022, 3:01 PM3
or 4
with it's equivalent -
or =
and add the the carry part to the next digit in left.ritesh
12/25/2022, 3:49 PMephemient
12/25/2022, 6:27 PMJakub Gwóźdź
12/25/2022, 6:28 PMi == 0L
or necessary .toInt()
here and there, whenever indices are needed. Then, before committing to repo, I switch back to ints 🙂Ozioma Ogbe
12/25/2022, 8:01 PMPaul Woitaschek
12/29/2022, 7:37 AM