Advent of Code 2021 day 3
12/03/2021, 5:00 AMDavid Whittaker
12/03/2021, 5:41 AMpavi2410
12/03/2021, 5:45 AM.clone()
or .copy()
method; ended up using .toMutableList
)pavi2410
12/03/2021, 5:47 AM.toString()
on a list of bits. 🤦♂️David Whittaker
12/03/2021, 5:47 AMvar oxyInput = input
and var co2Input = input
and then used filter
to reassign on each iterationpavi2410
12/03/2021, 5:49 AMknthmn
12/03/2021, 6:21 AMMarcin Wisniowski
12/03/2021, 6:41 AMDavid Whittaker
12/03/2021, 6:50 AMxor invert
I love it!Marcin Wisniowski
12/03/2021, 7:01 AMMichael Grigoryan
12/03/2021, 7:36 AMEmil Kantis
12/03/2021, 8:43 AMephemient
12/03/2021, 8:50 AMephemient
12/03/2021, 8:52 AM.retainAll()
on a MutableList
instead of re-assigning after .filter()
. it does some clever swapping in-place to avoid allocatingMichael Böiers
12/03/2021, 9:18 AMfun List<String>.day03(): Pair<Int, Int> {
fun part1(value: Boolean) = first().indices
.joinToString("") { if (moreCommon(it, value)) "1" else "0" }
.toInt(2)
fun part2(findMoreCommon: Boolean) = toMutableList().run {
for (bit in first().indices) {
val keep = moreCommon(bit, true).let { if (findMoreCommon) it else !it }
retainAll { it[bit] == keep.toChar() }
if (size == 1) break
}
first().toInt(2)
}
return part1(true) * part1(false) to part2(true) * part2(false)
}
private fun List<String>.moreCommon(bit: Int, value: Boolean) =
map { it[bit] }.count { it == value.toChar() } >= size / 2.0
private fun Boolean.toChar() = if (this) '1' else '0'
pavi2410
12/03/2021, 9:28 AMMichael Böiers
12/03/2021, 9:56 AMephemient
12/03/2021, 9:59 AMMichael Böiers
12/03/2021, 10:19 AMMichael de Kaste
12/03/2021, 11:19 AMJakub Gwóźdź
12/03/2021, 1:12 PMgammax
12/03/2021, 2:39 PMMichael de Kaste
12/03/2021, 2:41 PMgammax
12/03/2021, 2:53 PMcak
12/03/2021, 3:00 PMEdgars
12/03/2021, 3:44 PMtodd.ginsberg
12/03/2021, 3:56 PMsumOf
) to calculate the gamma.
For part 2 I took advantage of partition
and a fold
to successively pick either the largest or smallest side of the partition.
• Blog
• Code
Thankfully, I had the day off work today so I could focus on refactoring. 🙂Edgars
12/03/2021, 4:09 PMtodd.ginsberg
12/03/2021, 4:17 PMgnu
12/03/2021, 6:15 PMLuke
12/03/2021, 7:24 PMJakob Löhnertz
12/03/2021, 8:13 PMJack Bolles
12/03/2021, 8:53 PMEmil Kantis
12/03/2021, 8:53 PMJack Bolles
12/03/2021, 9:10 PMtodd.ginsberg
12/03/2021, 10:09 PMPaul Woitaschek
12/03/2021, 10:09 PMedrd
12/04/2021, 2:56 AMPaul Woitaschek
12/04/2021, 8:23 AMedrd
12/04/2021, 10:18 AM.map(Bit::flip)
(could have been .map(Boolean::not)
, but come on, the former looks neater 😄)Paul Woitaschek
12/04/2021, 10:22 AMMichael de Kaste
12/04/2021, 12:54 PMPaul Woitaschek
12/04/2021, 1:19 PMedrd
12/04/2021, 2:36 PMedrd
12/04/2021, 2:37 PMDan Fingal-Surma
12/05/2021, 9:06 AM