Skip to content

Commit d6cd72a

Browse files
committed
Solution 2017-19 (Particle Swarm)
1 parent cf2f45d commit d6cd72a

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package de.ronny_h.aoc.year2017.day19
2+
3+
import de.ronny_h.aoc.AdventOfCode
4+
import de.ronny_h.aoc.extensions.grids.Coordinates
5+
import de.ronny_h.aoc.extensions.grids.Direction
6+
import de.ronny_h.aoc.extensions.grids.Direction.*
7+
import de.ronny_h.aoc.extensions.grids.SimpleCharGrid
8+
9+
fun main() = ParticleSwarm().run("EOCZQMURF", "16312")
10+
11+
class ParticleSwarm : AdventOfCode<String>(2017, 19) {
12+
override fun part1(input: List<String>): String = RoutingDiagram(input).followThePath().letters
13+
14+
override fun part2(input: List<String>): String = RoutingDiagram(input).followThePath().length.toString()
15+
}
16+
17+
data class Path(val letters: String, val length: Int)
18+
19+
class RoutingDiagram(input: List<String>) : SimpleCharGrid(input, ' ') {
20+
fun findStartCoordinates(): Coordinates = find('|')
21+
22+
fun followThePath(): Path {
23+
val letters = mutableListOf<Char>()
24+
var position = findStartCoordinates()
25+
var direction = SOUTH
26+
var steps = 0
27+
28+
while (getAt(position) != nullElement) {
29+
if (getAt(position).isLetter()) {
30+
letters.add(getAt(position))
31+
}
32+
33+
position += direction
34+
steps++
35+
36+
if (getAt(position) == '+') {
37+
val turnRight = direction.turnRight()
38+
val charAtRight = getAt(position + turnRight)
39+
direction = if (charAtRight == turnRight.char() || charAtRight.isLetter()) {
40+
turnRight
41+
} else {
42+
direction.turnLeft()
43+
}
44+
}
45+
}
46+
return Path(letters.joinToString(""), steps)
47+
}
48+
49+
private fun Direction.char() = when (this) {
50+
NORTH -> '|'
51+
EAST -> '-'
52+
SOUTH -> '|'
53+
WEST -> '-'
54+
}
55+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package de.ronny_h.aoc.year2017.day19
2+
3+
import de.ronny_h.aoc.extensions.asList
4+
import de.ronny_h.aoc.extensions.grids.Coordinates
5+
import io.kotest.core.spec.style.StringSpec
6+
import io.kotest.matchers.shouldBe
7+
8+
class ParticleSwarmTest : StringSpec({
9+
10+
val input = """
11+
# |
12+
# | +--+
13+
# A | C
14+
# F---|----E|--+
15+
# | | | D
16+
# +B-+ +--+
17+
""".trimMargin("#").asList()
18+
19+
"input can be parsed" {
20+
RoutingDiagram(input).findStartCoordinates() shouldBe Coordinates(0, 4)
21+
}
22+
23+
"part 1: the letters on the path from the beginning to the end" {
24+
ParticleSwarm().part1(input) shouldBe "ABCDEF"
25+
}
26+
27+
"part 2: the package takes a total of 38 steps" {
28+
ParticleSwarm().part2(input) shouldBe "38"
29+
}
30+
})

0 commit comments

Comments
 (0)