Advent of Code 2021 in Kotlin, Day 3: Binary Diagnostic

preview_player
Показать описание

Solve some problems, learn some Kotlin lessons – and win some Kotlin swag this holiday season!

The "Advent of Code 2021 in Kotlin, Day 3: Binary Diagnostic" blog post:
Рекомендации по теме
Комментарии
Автор

By default, I use map or forEach and not for-loops, although the earlier sometimes do not allow to use break, then I switch to for-loop

Making these videos probably not so easy and takes time, but I hope to see all the solutions to this years aoc on this channel. I'd like to compare your approaches with mine. Thanks seb :)

cisimon
Автор

I learned about the `removeIf { }` function from this video. I also used mutable lists (would prefer to use immutable code but didn't know how to do in this task :D).

vitaliiplagov
Автор

I like the idiomatic Kotlin idea of data classes. Reminds me of named Tuples in Python. Maybe I'll start using that more often for clarity

EricMesa
Автор

I'm not to pleased with the mutabilities. Also I have to say I computed with the Ints themself not the strings.

jonathankolberg
Автор

Instead of iterating over the binary string to invert it, it should also be possible to do the same thing (likely much faster) with some math:

Create a bitmask of the same length as the input with (1 << (length + 1) - 1), then use inv() on the gammaRate integer, and return the result as a binary and of bitmask and inverse.

Less Kotlin specific features though, thus not as interesting. 😄

MaxrX
Автор

The functional form is much more concise and clear of intent than the imperative form. I also really like to avoid using mutating variables if possible.

dazraf
Автор

Complexity of your solution is O(n^2) but this is very slow, instead O(n)
fun part1(sequence: Sequence<String>) = sequence
.withIndex()
.map { (index, value) -> index to value.toCharArray().map { it.digitToInt() } }
.reduce { (indexAcc, acc), (index, arr) -> index to List(arr.size) { acc[it] + arr[it] } }
.let { (index, arr) -> List(arr.size) { if (arr[it] > index / 2) 1 to 0 else 0 to 1 } }
.unzip()
.let { (a, b) -> a.joinToString("").toLong(2) * b.joinToString("").toLong(2) }

skarloti