Skip to content

Commit f61ee1c

Browse files
committed
2022/Day 03
1 parent 161c837 commit f61ee1c

File tree

2 files changed

+18
-18
lines changed

2 files changed

+18
-18
lines changed

src/main/kotlin/me/grison/aoc/Collections.kt

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,4 +177,8 @@ fun <T> List<List<T>>.iterate(dimensions: Pair<Int, Int> = dimensions()): Sequen
177177
for (column in 0 until columns)
178178
yield(p(row, column))
179179
}
180-
}
180+
}
181+
182+
fun <T> List<Set<T>>.intersectAll() = this.reduce { a, b -> a.intersect(b) }
183+
fun <T> List<Set<T>>.unionAll() = this.reduce { a, b -> a.union(b) }
184+
fun List<String>.mapSet() = this.map { it.toSet() }

src/main/kotlin/me/grison/aoc/y2022/Day03.kt

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,29 +2,25 @@ package me.grison.aoc.y2022
22

33
import me.grison.aoc.Day
44
import me.grison.aoc.inTwo
5+
import me.grison.aoc.intersectAll
6+
import me.grison.aoc.mapSet
57

68
class Day03 : Day(3, 2022) {
79
override fun title() = "Rucksack Reorganization"
810

9-
override fun partOne() =
10-
inputList.sumOf { rucksack ->
11-
val common = commonItem(rucksack.inTwo().map { it.toSet() })
12-
itemPriority(common)
13-
}
11+
override fun partOne() = solve { rucksack -> rucksack.map { it.inTwo().mapSet() } }
1412

15-
override fun partTwo() =
16-
inputList
17-
.map { it.toSet() }
18-
.windowed(size = 3, step = 3)
19-
.sumOf { itemPriority(commonItem(it)) }
13+
override fun partTwo() = solve { it.mapSet().chunked(3) }
2014

21-
private fun commonItem(compartments: List<Set<Char>>) =
22-
compartments.reduce { a, b -> a.intersect(b) }.first()
15+
private fun solve(inputMixer: (List<String>) -> List<List<Set<Char>>>) =
16+
inputMixer(inputList).sumOf { itemPriority(it) }
2317

24-
private fun itemPriority(item: Char): Int =
25-
if (item.isLowerCase()) {
26-
1 + (item.code - 'a'.code)
27-
} else {
28-
27 + (item.code - 'A'.code)
18+
private fun itemPriority(compartments: List<Set<Char>>): Int =
19+
compartments.intersectAll().first().let { item ->
20+
if (item.isLowerCase()) {
21+
1 + (item.code - 'a'.code)
22+
} else {
23+
27 + (item.code - 'A'.code)
24+
}
2925
}
3026
}

0 commit comments

Comments
 (0)