-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c8bdffc
commit 0022ee0
Showing
3 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
Time: 44 70 70 80 | ||
Distance: 283 1134 1134 1491 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |