@@ -6,28 +6,29 @@ object Day2 {
66
77 type Report = Seq [Int ]
88
9- def isSafe (report : Report ): Boolean = {
10- val sorted = report.sorted
11- val increasing = report == sorted
12- val decreasing = report.reverse == sorted
13- val monotonic = increasing || decreasing
14- val safeDifferences = report.iterator.zipWithTail.forall({ case (a, b) =>
15- val diff = (a - b).abs
16- 1 <= diff && diff <= 3
17- })
18- monotonic && safeDifferences
19- }
9+ trait Part {
10+ def isSafe (report : Report ): Boolean
2011
21- object Part1 {
2212 def countSafe (reports : Seq [Report ]): Int = reports.count(isSafe)
2313 }
2414
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?
15+ object Part1 extends Part {
16+ override def isSafe (report : Report ): Boolean = {
17+ val sorted = report.sorted
18+ val increasing = report == sorted // TODO: add isSorted to library
19+ val decreasing = report.reverse == sorted // TODO: add isSorted to library (with Ordering)
20+ val monotonic = increasing || decreasing
21+ val safeDifferences = report.iterator.zipWithTail.forall({ case (a, b) =>
22+ (1 to 3 ).contains((a - b).abs)
23+ })
24+ monotonic && safeDifferences
2825 }
26+ }
2927
30- def countSafe (reports : Seq [Report ]): Int = reports.count(isSafe2)
28+ object Part2 extends Part {
29+ override def isSafe (report : Report ): Boolean = {
30+ Part1 .isSafe(report) || report.indices.exists(i => Part1 .isSafe(report.slice(0 , i) ++ report.slice(i + 1 , report.size))) // TODO: better seq removal? optimize?
31+ }
3132 }
3233
3334 def parseReports (input : String ): Seq [Report ] = input.linesIterator.map(_.split(" " ).map(_.toInt).toSeq).toSeq
0 commit comments