Skip to content

Commit

Permalink
✨ day 18
Browse files Browse the repository at this point in the history
  • Loading branch information
twentylemon committed Dec 18, 2024
1 parent 03ba748 commit b932673
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 0 deletions.
Binary file added src/main/resources/year2024/day18.txt
Binary file not shown.
27 changes: 27 additions & 0 deletions src/main/scala/org/lemon/advent/year2024/Day18.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package org.lemon.advent.year2024

import org.lemon.advent.lib.`2d`._
import org.lemon.advent.lib.graph._

private object Day18:

def parse(input: String) = input.linesIterator.map(_ match
case s"$x,$y" => Coord(x.toInt, y.toInt)
).toSeq

def adjacency(area: Area, corrupt: Set[Coord])(coord: Coord): Seq[Coord] =
coord.adjacent.filterNot(corrupt).filter(area.contains)

def part1(input: String, example: Boolean = false, take: Int = 1024) =
val area = if example then Area(0 to 6, 0 to 6) else Area(0 to 70, 0 to 70)
val corrupt = parse(input).take(take).toSet
pathFind(adjacency(area, corrupt), Coord(0, 0), area.bottomRight).get.distance

def part2(input: String, example: Boolean = false) =
val area = if example then Area(0 to 6, 0 to 6) else Area(0 to 70, 0 to 70)
val bytes = parse(input)
val lastPossible = bytes.reverse.tails.find(bits =>
pathFind(adjacency(area, bits.toSet), Coord(0, 0), area.bottomRight).isDefined
).get
val impossible = bytes(lastPossible.size)
s"${impossible.x},${impossible.y}"
72 changes: 72 additions & 0 deletions src/test/scala/org/lemon/advent/year2024/Day18Test.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package org.lemon.advent.year2024

import org.lemon.advent._
import org.lemon.advent.year2024.Day18._

class Day18Test extends UnitTest:

test("part 1 example") {
val in = """|5,4
|4,2
|4,5
|3,0
|2,1
|6,3
|2,4
|1,5
|0,6
|3,3
|2,6
|5,1
|1,2
|5,5
|2,5
|6,5
|1,4
|0,4
|6,4
|1,1
|6,1
|1,0
|0,5
|1,6
|2,0""".stripMargin
part1(in, example = true, take = 12) shouldBe 22
}

test("part 1") {
part1(read(file(2024)(18))) shouldBe 338
}

test("part 2 example") {
val in = """|5,4
|4,2
|4,5
|3,0
|2,1
|6,3
|2,4
|1,5
|0,6
|3,3
|2,6
|5,1
|1,2
|5,5
|2,5
|6,5
|1,4
|0,4
|6,4
|1,1
|6,1
|1,0
|0,5
|1,6
|2,0""".stripMargin
part2(in, example = true) shouldBe "6,1"
}

test("part 2") {
part2(read(file(2024)(18))) shouldBe "20,44"
}

0 comments on commit b932673

Please sign in to comment.