@@ -2,21 +2,25 @@ package de.ronny_h.aoc.year24.day23
22
33import de.ronny_h.aoc.AdventOfCode
44
5- fun main () = LANParty ().run (1240 , 0 )
5+ fun main () = LANParty ().run (" 1240" , " am,aq,by,ge,gf,ie,mr,mt,rw,sn,te,yi,zb " )
66
7- class LANParty : AdventOfCode <Int >(2024 , 23 ) {
7+ class LANParty : AdventOfCode <String >(2024 , 23 ) {
88
9- override fun part1 (input : List <String >): Int = Network (input)
9+ override fun part1 (input : List <String >): String = Network (input)
1010 .searchForLANPartiesWithThreeComputers()
11- .filter { set -> set.any { it.startsWith(" t" ) } }.size
11+ .filter { set -> set.any { it.startsWith(" t" ) } }
12+ .size
13+ .toString()
1214
13- override fun part2 (input : List <String >): Int {
14- TODO (" Not yet implemented" )
15- }
15+ override fun part2 (input : List <String >): String = Network (input)
16+ .sortedConnectionSets()
17+ .findLargestIntersection()
18+ .sorted()
19+ .joinToString(" ," )
1620}
1721
1822class Network (input : List <String >) {
19- // from one computer to all others it is directly connected to
23+ // a map entry for computer `c` contains all other computers that `c` is directly connected to
2024 private val connections: Map <String , Set <String >>
2125
2226 init {
@@ -33,14 +37,38 @@ class Network(input: List<String>) {
3337 val triples = mutableSetOf<Set <String >>()
3438 connections.forEach { (computer, neighbors) ->
3539 neighbors.forEach { neighbor ->
36- val otherNeighborsNeighbors = connections.getValue(neighbor).filterNot { it == computer }
40+ val neighborsOtherNeighbors = connections.getValue(neighbor).filterNot { it == computer }
3741 val neighborsWithBacklinkToComputer =
38- otherNeighborsNeighbors .filter { connections.getValue(it).contains(computer) }
42+ neighborsOtherNeighbors .filter { connections.getValue(it).contains(computer) }
3943 neighborsWithBacklinkToComputer.forEach {
4044 triples.add(setOf (computer, neighbor, it))
4145 }
4246 }
4347 }
4448 return triples
4549 }
50+
51+ fun sortedConnectionSets () = connections
52+ .map { (computer, neighbors) -> neighbors + computer }
53+ .sortedBy { - it.size }
54+ }
55+
56+ fun List<Set<String>>.findLargestIntersection (): Set <String > {
57+ // precondition: `this` is sorted in decreasing order by size
58+ var largestIntersection = emptySet<String >()
59+ for ((i, s1) in this .withIndex()) {
60+ for ((j, s2) in this .withIndex()) {
61+ if (i == j) continue
62+ if (s2.size < largestIntersection.size) {
63+ return largestIntersection
64+ }
65+ val intersection = s1 intersect s2
66+ if (intersection.size > largestIntersection.size) {
67+ if (this .count { it.containsAll(intersection) } == intersection.size) {
68+ largestIntersection = intersection
69+ }
70+ }
71+ }
72+ }
73+ return largestIntersection
4674}
0 commit comments