Skip to content

Commit

Permalink
❇️ day 6
Browse files Browse the repository at this point in the history
  • Loading branch information
twentylemon committed Dec 6, 2023
1 parent c8bdffc commit 0022ee0
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/main/resources/year2023/day06.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Time: 44 70 70 80
Distance: 283 1134 1134 1491
28 changes: 28 additions & 0 deletions src/main/scala/org/lemon/advent/year2023/Day06.scala
Original file line number Diff line number Diff line change
@@ -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)
25 changes: 25 additions & 0 deletions src/test/scala/org/lemon/advent/year2023/Day06Test.scala
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 0022ee0

Please sign in to comment.