Skip to content

Commit 6911ace

Browse files
committed
feat(aoc-2023): add day 6 part 1 and part 2
1 parent 97de732 commit 6911ace

2 files changed

Lines changed: 58 additions & 3 deletions

File tree

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,42 @@
11
package com.markkovari.adventofcode.day06
22

3-
def part1(input: String): Long = 288
3+
// Oh boy, did I port this https://github.com/tlareg/advent-of-code/blob/master/src/2023/day06/index.ts ?
4+
// I sure did
45

5-
def part2(input: String): Long = 2
6+
type Race = (Long, Long)
7+
8+
def part1(input: String): Long = {
9+
// should not collect iterator to array, but I'm lazy, just like my algorithms
10+
val lines = input.linesIterator.toArray
11+
val times = lines(0).split("\\s+").drop(1).map(_.toInt)
12+
val distances = lines(1).split("\\s+").drop(1).map(_.toInt)
13+
val races = times.map(_.toLong).zip(distances.map(_.toLong))
14+
solveForRaces(races)
15+
}
16+
17+
def solveForRaces(races: Array[Race]): Long = {
18+
races
19+
.map((a, b) => getNumberOfWaysBeatingRecord(a, b))
20+
.product
21+
}
22+
23+
def getNumberOfWaysBeatingRecord(raceTime: Long, recordDistance: Long): Long = {
24+
(0 until raceTime.toInt)
25+
.map(holdTime => getDistance(holdTime, raceTime))
26+
.count(distanceByHold => distanceByHold > recordDistance)
27+
}
28+
29+
def getDistance(holdTime: Long, raceTime: Long): Long =
30+
holdTime * (raceTime - holdTime)
31+
32+
def part2(input: String): Long = {
33+
val lines = input.linesIterator.toArray
34+
val time = parseLineForPart2(lines(0))
35+
val distance = parseLineForPart2(lines(1))
36+
solveForRaces(Array[Race]((time, distance)))
37+
}
38+
39+
def parseLineForPart2(line: String): Long = {
40+
val num = line.split(":")(1).trim().split("\\s+").mkString
41+
num.toLong
42+
}

2023/src/test/scala/com/markkovari/adventofcode/Day06Tests.scala

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package com.markkovari.adventofcode
22

3-
import com.markkovari.adventofcode.day06.part1
3+
import com.markkovari.adventofcode.day06.*
44
import org.scalatest.funsuite.AnyFunSuite
55

66
import scala.io.Source
@@ -11,4 +11,22 @@ class Day06Tests extends AnyFunSuite {
1111
assert(part1(source.mkString) === 288)
1212
source.close()
1313
}
14+
15+
test("Part1 solution") {
16+
val source = io.Source.fromFile("./src/test/resources/6/values")
17+
assert(part1(source.mkString) === 4403592)
18+
source.close()
19+
}
20+
21+
test("Part2 example") {
22+
val source = io.Source.fromFile("./src/test/resources/6/example_1")
23+
assert(part2(source.mkString) === 71503)
24+
source.close()
25+
}
26+
27+
test("Part2 solution") {
28+
val source = io.Source.fromFile("./src/test/resources/6/values")
29+
assert(part2(source.mkString) === 38017587)
30+
source.close()
31+
}
1432
}

0 commit comments

Comments
 (0)