@@ -26,32 +26,39 @@ data class Grid(val height: Int, val width: Int, val antennae: AntennaMap) {
2626 * 2. pos2 - delta
2727 * and if they are in the grid, then they contribute.
2828 */
29- private fun calculateAntinodePair (pos1 : Position , pos2 : Position ): List <Position > {
29+ private fun calculateAntinodePair (pos1 : Position , pos2 : Position ): Set <Position > {
3030 val delta = pos1 - pos2
3131 return listOf (pos1 + delta, pos2 - delta)
32- .filter { (row, col) -> row in ( 0 until height) && col in ( 0 until width) }
33- .also { it.forEach { t -> println ( " For $pos1 + $pos2 -> $t " ) }}
32+ .filter(::inGrid)
33+ .toSet()
3434 }
3535
36+ private fun inGrid (pos : Position ): Boolean =
37+ pos.first in (0 until height) && pos.second in (0 until width)
38+
3639 /* *
3740 * Calculate the slope of the line that the antinodes are on, namely
3841 * pos1 - pos2
3942 * and then continue to calculate all possible other candidates (including themselves).
4043 */
4144 private fun calculateAllAntinodes (pos1 : Position , pos2 : Position ): Set <Position > {
4245 val delta = pos1 - pos2
43- tailrec fun aux (newAntinodes : Set <Position > = setOf(pos1, pos2),
44- antinodes : Set <Position > = emptySet()): Set <Position > = when {
45- newAntinodes.isEmpty() -> antinodes
46- else -> {
47- val possibleNewAntinodes = newAntinodes.flatMap { listOf (it + delta, it - delta) }
48- .toSet()
49- .filter { (row, col) -> row in (0 until height) && col in (0 until width) }
50- .toSet()
51- aux(possibleNewAntinodes, antinodes + newAntinodes)
52- }
53- }
54- return aux()
46+ val antinodes = mutableSetOf<Position >()
47+ val currAntinodes = mutableSetOf<Position >(pos1, pos2)
48+ while (currAntinodes.isNotEmpty()) {
49+ antinodes + = currAntinodes
50+ val nextAntinodes = mutableSetOf<Position >()
51+
52+ for (antinode in currAntinodes) {
53+ val candidate1 = antinode - delta
54+ if (inGrid(candidate1) && candidate1 !in antinodes) nextAntinodes.add(candidate1)
55+ val candidate2 = antinode + delta
56+ if (inGrid(candidate2) && candidate2 !in antinodes) nextAntinodes.add(candidate2)
57+ }
58+ currAntinodes.clear()
59+ currAntinodes + = nextAntinodes
60+ }
61+ return antinodes
5562 }
5663
5764 /* *
@@ -117,6 +124,6 @@ fun main() {
117124 // Part 1: 376
118125 println (" Part 1: ${answer1(input)} " )
119126
120- // Part 2:
121- // println("Part 2: ${answer2(input)}")
127+ // Part 2: 1352
128+ println (" Part 2: ${answer2(input)} " )
122129}
0 commit comments