diff --git a/src/main/resources/year2023/day06.txt b/src/main/resources/year2023/day06.txt new file mode 100644 index 0000000..fd9b512 --- /dev/null +++ b/src/main/resources/year2023/day06.txt @@ -0,0 +1,2 @@ +Time: 44 70 70 80 +Distance: 283 1134 1134 1491 diff --git a/src/main/scala/org/lemon/advent/year2023/Day06.scala b/src/main/scala/org/lemon/advent/year2023/Day06.scala new file mode 100644 index 0000000..9260b91 --- /dev/null +++ b/src/main/scala/org/lemon/advent/year2023/Day06.scala @@ -0,0 +1,28 @@ +package org.lemon.advent.year2023 + +private object Day06: + def parse(input: String) = + val ins = input.linesIterator + .map(_ match + case s"$_: $nums" => nums.split(" ").map(_.trim).map(_.toLongOption).flatten.toSeq + ) + .toSeq + ins(0).zip(ins(1)) + + def quadratic(time: Long, dist: Long) = + val (a, b, c) = (-1, time, -(dist + 1)) // dist+1 because we need to beat them + val t1 = (-b + math.sqrt(b * b - 4 * a * c)) / (2 * a) + val t2 = (-b - math.sqrt(b * b - 4 * a * c)) / (2 * a) + println((t1, t2)) + if t1.isNaN || t2.isNaN then 0 + else (math.floor(math.max(t1, t2)) - math.ceil(math.min(t1, t2)) + 1).toLong + + def part1(input: String) = parse(input) + .map(quadratic) + .product + + def part2(input: String) = + val single = parse(input) + .map((t, d) => (t.toString, d.toString)) + .reduce { case ((t1, d1), (t2, d2)) => (t1 + t2, d1 + d2) } + quadratic(single._1.toLong, single._2.toLong) diff --git a/src/test/scala/org/lemon/advent/year2023/Day06Test.scala b/src/test/scala/org/lemon/advent/year2023/Day06Test.scala new file mode 100644 index 0000000..fccdcda --- /dev/null +++ b/src/test/scala/org/lemon/advent/year2023/Day06Test.scala @@ -0,0 +1,25 @@ +package org.lemon.advent.year2023 + +import org.lemon.advent._ +import org.lemon.advent.year2023.Day06._ + +class Day06Test extends UnitTest: + + val in = """|Time: 7 15 30 + |Distance: 9 40 200""".stripMargin + + test("part 1 example") { + part1(in) shouldBe 288 + } + + test("part 1") { + part1(read(file(2023)(6))) shouldBe 219849 + } + + test("part 2 example") { + part2(in) shouldBe 71503 + } + + test("part 2") { + part2(read(file(2023)(6))) shouldBe 29432455L + }