Skip to content

Instantly share code, notes, and snippets.

@sungkmi
Created February 25, 2022 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sungkmi/ad6fddec83c3c21587102998eb292507 to your computer and use it in GitHub Desktop.
Save sungkmi/ad6fddec83c3c21587102998eb292507 to your computer and use it in GitHub Desktop.
package lascala.aoc2021.day11_20.day13
opaque type TransparentPaper = Set[(Int, Int)]
enum FoldInstruction:
case FoldUp(y: Int) extends FoldInstruction
case FoldLeft(x: Int) extends FoldInstruction
object FoldInstruction:
def parse(line: String): FoldInstruction =
val Array(xy, coord) = line.drop("fold along ".size).split("=")
xy match
case "x" => FoldLeft(coord.toInt)
case "y" => FoldUp(coord.toInt)
case _ => throw new IllegalArgumentException(s"Unknown coordinate: $xy")
extension (p: TransparentPaper)
def fold(instruction: FoldInstruction): TransparentPaper =
instruction match
case FoldInstruction.FoldUp(y1) =>
p.map { case (x, y) => (x, y1 - (y1 - y).abs) }
case FoldInstruction.FoldLeft(x1) =>
p.map { case (x, y) => (x1 - (x1 - x).abs, y) }
def print: String =
val xs = p.map(_._1)
val ys = p.map(_._2)
(ys.min to ys.max)
.map { y =>
(xs.min to xs.max).map { x =>
if p.contains((x, y)) then '#' else '.'
}.mkString
}
.mkString("\n")
def parse(s: String): (TransparentPaper, List[FoldInstruction]) =
val Array(coordinates, instructionLines) = s.split("\n\n")
val paper =
for line <- coordinates.split("\n").toSet
yield
val Array(x, y) = line.split(",").map(_.toInt)
(x, y)
val instructions =
instructionLines.split("\n").toList.map(FoldInstruction.parse)
(paper, instructions)
def solve1(s: String): BigInt =
val (paper, instructions) = parse(s)
paper.fold(instructions.head).size
end solve1
def solve2(s: String): String =
val (paper, instructions) = parse(s)
val p1 = instructions.foldLeft(paper)(_ `fold` _)
p1.print
end solve2
@main def part1: Unit =
val ans = solve1(input)
println(ans)
@main def part2: Unit =
val ans = solve2(input)
println(ans)
//val input = """462,575
package lascala.aoc2021.day11_20.day13
import minitest.SimpleTestSuite
import hedgehog.minitest.HedgehogSupport
import hedgehog.*
object Day13Test extends SimpleTestSuite with HedgehogSupport:
val testInput = """6,10
0,14
9,10
0,3
10,4
4,11
6,0
6,12
4,1
0,13
10,12
3,4
3,0
8,4
1,10
2,14
8,10
9,0
fold along y=7
fold along x=5"""
example("day13 - solve 1") {
solve1(testInput) ==== 17
}
example("day13 - solve 2") {
val expected = """#####
#...#
#...#
#...#
#####"""
solve2(testInput) ==== expected
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment