Skip to content

Commit

Permalink
2023 - Day 15 - part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
fmmr committed Dec 15, 2023
1 parent 61eb2db commit e720bbe
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 9 deletions.
53 changes: 46 additions & 7 deletions src/main/kotlin/no/rodland/advent_2023/Day15.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,63 @@ import no.rodland.advent.Day
// template generated: 15/12/2023
// Fredrik Rødland 2023

class Day15(val input: List<String>) : Day<Int, Long, List<CharArray>> {
class Day15(val input: List<String>) : Day<Int, Int, List<Day15.Step>> {

private val parsed = input.parse()

override fun partOne(): Int {
return parsed.sumOf { it.hash() }
return parsed.sumOf { it.hash }
}

private fun CharArray.hash() = fold(0) { acc, c -> ((c.code + acc) * 17).mod(256) }
override fun partTwo(): Int {
val ar = Array(256) { mutableListOf<Lens>() }
parsed.forEach { step ->
ar[step.label.hash()].also { box ->
if (step.isMinus) {
box.remove(step.label)
} else {
box.replace(step.label, step)
}
}
}
return ar.flatMapIndexed { idx, list ->
list.mapIndexed { listIdx, lens -> focusingPower(idx, listIdx, lens) }
}.sum()
}

private fun focusingPower(boxIndex: Int, lensIndex: Int, lens: Lens) = (boxIndex + 1) * (lensIndex + 1) * lens.focal

private fun MutableList<Lens>.remove(label: String) {
removeAll { it.label == label }
}

override fun partTwo(): Long {
return 2
private fun MutableList<Lens>.replace(label: String, step: Step) {
Lens(label, step.num!!).also { lens ->
indexOfFirst { it.label == label }.also { if (it >= 0) this[it] = lens else add(lens) }
}
}

override fun List<String>.parse(): List<CharArray> {
return first().split(",").map { it.toCharArray() }
data class Lens(val label: String, val focal: Int)

data class Step(val str: String) {
val label = str.split("=", "-")[0]
val num: Int? = str.split("=").let {
if (it.size == 2) {
it[1].toInt()
} else {
null
}
}
val isMinus = num == null
val hash = str.hash()
}

override fun List<String>.parse(): List<Step> {
return first().split(",").map { Step(it) }
}

override val day = "15".toInt()
}

fun String.hash() = fold(0) { acc, c -> ((c.code + acc) * 17).mod(256) }

4 changes: 2 additions & 2 deletions src/test/kotlin/no/rodland/advent_2023/Day15Test.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ internal class Day15Test {
private val test15 = "2023/input_15_test.txt".readFile()

private val resultTestOne = 1320
private val resultTestTwo = 2L
private val resultTestTwo = 145
private val resultOne = 522547
private val resultTwo = 2L
private val resultTwo = 229271

val test = defaultTestSuiteParseOnInit(
Day15(data15),
Expand Down

0 comments on commit e720bbe

Please sign in to comment.