From 91bb259459d29e4345767d7d0cbdf292c688a6f1 Mon Sep 17 00:00:00 2001 From: scarf Date: Mon, 2 Sep 2024 00:02:35 +0900 Subject: [PATCH] feat: day 8 --- 2015/Day8.scala | 31 +++++++++++++++++++++++++++++++ 2015/Day8.test.scala | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 2015/Day8.scala create mode 100644 2015/Day8.test.scala diff --git a/2015/Day8.scala b/2015/Day8.scala new file mode 100644 index 0000000..3c33744 --- /dev/null +++ b/2015/Day8.scala @@ -0,0 +1,31 @@ +package day8 + +import scala.io.Source.fromFile +import scala.util.chaining.* + +extension (s: String) + def memoryLen = decode(s.toList).size - 2 + def encodedLen = encode(s.toList).size + 2 + +def decode(sx: List[Char]): List[Char] = sx match + case '\\' :: '\\' :: xs => '\\' +: decode(xs) + case '\\' :: '"' :: xs => '"' +: decode(xs) + case '\\' :: 'x' :: _ :: _ :: xs => 'x' +: decode(xs) + case x :: xs => x +: decode(xs) + case Nil => Nil + +def encode(sx: List[Char]): List[Char] = sx match + case '\\' :: xs => '\\' +: '\\' +: encode(xs) + case '"' :: xs => '\\' +: '"' +: encode(xs) + case x :: xs => x +: encode(xs) + case Nil => Nil + +def part1(s: String) = s.size - s.memoryLen +def part2(s: String) = s.encodedLen - s.size + +@main def main() = + val input = + fromFile(".cache/08.txt").getLines.toVector.map(_.trim) + + input.map(part1).sum.pipe(println) + input.map(part2).sum.pipe(println) diff --git a/2015/Day8.test.scala b/2015/Day8.test.scala new file mode 100644 index 0000000..d446a89 --- /dev/null +++ b/2015/Day8.test.scala @@ -0,0 +1,38 @@ +import munit.FunSuite +import day8.* + +class Day8Tests extends FunSuite: + val xs = Seq( + """""""" -> (2, 0), + """"abc"""" -> (5, 3), + """"aaa\"aaa"""" -> (10, 7), + """"\x27"""" -> (6, 1), + ) + + xs.foreach { (x, rest) => + val (literalLen, memoryLen) = rest + test(s"part1 [$x]"): + assertEquals(x.size, literalLen) + assertEquals(x.memoryLen, memoryLen) + assertEquals(part1(x), literalLen - memoryLen) + } + + test("part1"): + assertEquals(xs.map(_._1).map(part1).sum, 12) + + val ys = Seq( + """""""" -> (2, 6), + """"abc"""" -> (5, 9), + """"aaa\"aaa"""" -> (10, 16), + """"\x27"""" -> (6, 11), + ) + + ys.foreach { (y, rest) => + val (literalLen, encodedLen) = rest + assertEquals(y.size, literalLen) + assertEquals(y.encodedLen, encodedLen) + assertEquals(part2(y), encodedLen - literalLen) + } + + test("part2"): + assertEquals(ys.map(_._1).map(part2).sum, 19)