Skip to content

Commit

Permalink
feat: 2024 day 2
Browse files Browse the repository at this point in the history
  • Loading branch information
scarf005 committed Dec 2, 2024
1 parent 30f7f0e commit 2044824
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
24 changes: 24 additions & 0 deletions 2024/day02.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package `2024`.day02

import prelude.*

def safe(xs: Seq[Int]) =
val isDesc = xs(0) > xs(1)
xs.sliding(2).forall { case Seq(a, b) =>
(if isDesc then a > b else a < b) && (1 to 3).contains((a - b).abs)
}

def withoutOnes[A](xs: Seq[A]) =
xs.zipWithIndex.map((_, i) => xs.patch(i, Nil, 1))

def part1(xss: Seq[Seq[Int]]): Int = xss.count(safe)

def part2(xss: Seq[Seq[Int]]): Int =
xss.count(xs => safe(xs) || withoutOnes(xs).exists(safe))

@main def main() =
val input =
readInput(this).getLines.map(_.split(" ").map(_.toInt).toVector).toVector

println(part1(input))
println(part2(input))
27 changes: 27 additions & 0 deletions 2024/day02.test.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package `2024`.day02

import munit.FunSuite

val example = Vector(
Vector(7, 6, 4, 2, 1),
Vector(1, 2, 7, 8, 9),
Vector(9, 7, 6, 2, 1),
Vector(1, 3, 2, 4, 5),
Vector(8, 6, 4, 4, 1),
Vector(1, 3, 6, 7, 9),
)

class Test extends FunSuite:
test("part 1"):
assertEquals(safe(Vector(7, 6, 4, 2, 1)), true) // decreasing by 1 or 2
assertEquals(safe(Vector(1, 2, 7, 8, 9)), false) // increase of 5
assertEquals(safe(Vector(9, 7, 6, 2, 1)), false) // decrease of 4
assertEquals(safe(Vector(1, 3, 2, 4, 5)), false) // not monotonic
assertEquals(safe(Vector(8, 6, 4, 4, 1)), false) // no change
assertEquals(safe(Vector(1, 3, 6, 7, 9)), true) // increasing by 1-3

test("part 1"):
assertEquals(part1(example), 2)

test("part 2"):
assertEquals(part2(example), 4)

0 comments on commit 2044824

Please sign in to comment.