generated from Jadarma/advent-of-code-kotlin-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathY2024D23.kt
56 lines (47 loc) · 1.95 KB
/
Y2024D23.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package aockt.y2024
import aockt.util.parse
import io.github.jadarma.aockt.core.Solution
object Y2024D23 : Solution {
/**
* Find all subsets of nodes such that every element has [connections] to every other, with at most [limit] nodes.
* The nodes in the cliques are sorted alphabetically.
*/
private fun cliques(
connections: Map<String, Set<String>>,
limit: Int = Int.MAX_VALUE,
): Set<List<String>> = buildSet {
fun recurse(node: String, clique: Set<String>) {
clique.sorted()
.takeUnless { it in this }
?.also(::add)
?.takeIf { it.size < limit }
?: return
for (neighbor in connections.getValue(node)) {
if (neighbor in clique) continue
if (!connections.getValue(neighbor).containsAll(clique)) continue
recurse(neighbor, clique + neighbor)
}
}
for (x in connections.keys) recurse(x, setOf(x))
}
/** Parse the [input] and return a connection map from a computer to all directly linked computers from the LAN. */
private fun parseInput(input: String): Map<String, Set<String>> = parse {
buildMap {
input
.lineSequence()
.map { it.split('-', limit = 2) }
.forEach { (a, b) ->
compute(a) { _, cons -> ((cons ?: mutableSetOf()) as MutableSet<String>).apply { add(b) } }
compute(b) { _, cons -> ((cons ?: mutableSetOf()) as MutableSet<String>).apply { add(a) } }
}
}
}
override fun partOne(input: String): Int =
cliques(parseInput(input), limit = 3)
.filter { it.size == 3 }
.count { it.any { node -> node.startsWith('t') } }
override fun partTwo(input: String): String =
cliques(parseInput(input), limit = 99)
.maxBy { it.size }
.joinToString(",")
}