Skip to content

Commit 59add91

Browse files
committed
Solution 2017-12 (Digital Plumber)
1 parent cb276a3 commit 59add91

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package de.ronny_h.aoc.year2017.day12
2+
3+
import de.ronny_h.aoc.AdventOfCode
4+
5+
fun main() = DigitalPlumber().run(134, 193)
6+
7+
class DigitalPlumber : AdventOfCode<Int>(2017, 12) {
8+
override fun part1(input: List<String>): Int = input.parseDirectConnections().groupOf(0).size
9+
10+
override fun part2(input: List<String>): Int {
11+
val connections = input.parseDirectConnections()
12+
13+
val groups = mutableListOf<List<Int>>()
14+
connections.keys.forEach { programId ->
15+
if (groups.none { it.contains(programId) }) {
16+
groups.add(connections.groupOf(programId))
17+
}
18+
}
19+
20+
return groups.size
21+
}
22+
23+
private fun List<String>.parseDirectConnections(): Map<Int, List<Int>> = associate {
24+
val (programId, connections) = it.split(" <-> ")
25+
programId.toInt() to connections.split(", ").map(String::toInt)
26+
}
27+
28+
private fun Map<Int, List<Int>>.groupOf(start: Int): List<Int> {
29+
val group = mutableListOf(start)
30+
fun addTransitiveConnectionsOf(programId: Int) {
31+
this[programId]?.forEach {
32+
if (!group.contains(it)) {
33+
group.add(it)
34+
addTransitiveConnectionsOf(it)
35+
}
36+
}
37+
}
38+
addTransitiveConnectionsOf(start)
39+
return group
40+
}
41+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package de.ronny_h.aoc.year2017.day12
2+
3+
import de.ronny_h.aoc.extensions.asList
4+
import io.kotest.core.spec.style.StringSpec
5+
import io.kotest.matchers.shouldBe
6+
7+
class DigitalPlumberTest : StringSpec({
8+
9+
val input = """
10+
0 <-> 2
11+
1 <-> 1
12+
2 <-> 0, 3, 4
13+
3 <-> 2, 4
14+
4 <-> 2, 3, 6
15+
5 <-> 6
16+
6 <-> 4, 5
17+
""".asList()
18+
19+
"part 1: the number of programs in the group that contains program ID 0" {
20+
DigitalPlumber().part1(input) shouldBe 6
21+
}
22+
23+
"part 2: the number of groups in total" {
24+
DigitalPlumber().part2(input) shouldBe 2
25+
}
26+
})

0 commit comments

Comments
 (0)