Skip to content

Commit

Permalink
feat: day 8
Browse files Browse the repository at this point in the history
  • Loading branch information
scarf005 committed Sep 1, 2024
1 parent 8b542f4 commit 91bb259
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
31 changes: 31 additions & 0 deletions 2015/Day8.scala
Original file line number Diff line number Diff line change
@@ -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)
38 changes: 38 additions & 0 deletions 2015/Day8.test.scala
Original file line number Diff line number Diff line change
@@ -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)

0 comments on commit 91bb259

Please sign in to comment.