Skip to content

Commit 07a9fee

Browse files
committed
Solve 2024 day 2 part 2
1 parent 8f2cd76 commit 07a9fee

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

src/main/scala/eu/sim642/adventofcode2024/Day2.scala

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,24 @@ object Day2 {
1818
monotonic && safeDifferences
1919
}
2020

21-
def countSafe(reports: Seq[Report]): Int = reports.count(isSafe)
21+
object Part1 {
22+
def countSafe(reports: Seq[Report]): Int = reports.count(isSafe)
23+
}
24+
25+
object Part2 {
26+
private def isSafe2(report: Report): Boolean = {
27+
isSafe(report) || report.indices.exists(i => isSafe(report.slice(0, i) ++ report.slice(i + 1, report.size))) // TODO: better seq removal? optimize?
28+
}
29+
30+
def countSafe(reports: Seq[Report]): Int = reports.count(isSafe2)
31+
}
2232

2333
def parseReports(input: String): Seq[Report] = input.linesIterator.map(_.split(" ").map(_.toInt).toSeq).toSeq
2434

2535
lazy val input: String = scala.io.Source.fromInputStream(getClass.getResourceAsStream("day2.txt")).mkString.trim
2636

2737
def main(args: Array[String]): Unit = {
28-
println(countSafe(parseReports(input)))
38+
println(Part1.countSafe(parseReports(input)))
39+
println(Part2.countSafe(parseReports(input)))
2940
}
3041
}

src/test/scala/eu/sim642/adventofcode2024/Day2Test.scala

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,18 @@ class Day2Test extends AnyFunSuite {
1414
|1 3 6 7 9""".stripMargin
1515

1616
test("Part 1 examples") {
17-
assert(countSafe(parseReports(exampleInput)) == 2)
17+
assert(Part1.countSafe(parseReports(exampleInput)) == 2)
1818
}
1919

2020
test("Part 1 input answer") {
21-
assert(countSafe(parseReports(input)) == 549)
21+
assert(Part1.countSafe(parseReports(input)) == 549)
2222
}
2323

2424
test("Part 2 examples") {
25+
assert(Part2.countSafe(parseReports(exampleInput)) == 4)
2526
}
2627

2728
test("Part 2 input answer") {
29+
assert(Part2.countSafe(parseReports(input)) == 589)
2830
}
2931
}

0 commit comments

Comments
 (0)