From 0299c43a9f8de19ed77047a0f039cacad22f98ac Mon Sep 17 00:00:00 2001 From: Docusaurus bot Date: Wed, 11 Dec 2024 16:07:41 +0000 Subject: [PATCH] Deploy website - based on 4b1679a5aef8baa10202cd352887c70bd5da0a39 --- 2021/index.html | 4 ++-- 2022/index.html | 4 ++-- 2022/puzzles/day01/index.html | 4 ++-- 2022/puzzles/day02/index.html | 4 ++-- 2022/puzzles/day03/index.html | 4 ++-- 2022/puzzles/day04/index.html | 4 ++-- 2022/puzzles/day05/index.html | 4 ++-- 2022/puzzles/day06/index.html | 4 ++-- 2022/puzzles/day07/index.html | 4 ++-- 2022/puzzles/day08/index.html | 4 ++-- 2022/puzzles/day09/index.html | 4 ++-- 2022/puzzles/day10/index.html | 4 ++-- 2022/puzzles/day11/index.html | 4 ++-- 2022/puzzles/day12/index.html | 4 ++-- 2022/puzzles/day13/index.html | 4 ++-- 2022/puzzles/day14/index.html | 4 ++-- 2022/puzzles/day15/index.html | 4 ++-- 2022/puzzles/day16/index.html | 4 ++-- 2022/puzzles/day17/index.html | 4 ++-- 2022/puzzles/day18/index.html | 4 ++-- 2022/puzzles/day19/index.html | 4 ++-- 2022/puzzles/day20/index.html | 4 ++-- 2022/puzzles/day21/index.html | 4 ++-- 2022/puzzles/day22/index.html | 4 ++-- 2022/puzzles/day23/index.html | 4 ++-- 2022/puzzles/day24/index.html | 4 ++-- 2022/puzzles/day25/index.html | 4 ++-- 2023/index.html | 4 ++-- 2023/puzzles/day01/index.html | 4 ++-- 2023/puzzles/day02/index.html | 4 ++-- 2023/puzzles/day03/index.html | 4 ++-- 2023/puzzles/day04/index.html | 4 ++-- 2023/puzzles/day05/index.html | 4 ++-- 2023/puzzles/day06/index.html | 4 ++-- 2023/puzzles/day07/index.html | 4 ++-- 2023/puzzles/day08/index.html | 4 ++-- 2023/puzzles/day09/index.html | 4 ++-- 2023/puzzles/day10/index.html | 4 ++-- 2023/puzzles/day11/index.html | 4 ++-- 2023/puzzles/day12/index.html | 4 ++-- 2023/puzzles/day13/index.html | 4 ++-- 2023/puzzles/day14/index.html | 4 ++-- 2023/puzzles/day15/index.html | 4 ++-- 2023/puzzles/day16/index.html | 4 ++-- 2023/puzzles/day17/index.html | 4 ++-- 2023/puzzles/day18/index.html | 4 ++-- 2023/puzzles/day19/index.html | 4 ++-- 2023/puzzles/day20/index.html | 4 ++-- 2023/puzzles/day21/index.html | 4 ++-- 2023/puzzles/day22/index.html | 4 ++-- 2023/puzzles/day23/index.html | 4 ++-- 2023/puzzles/day24/index.html | 4 ++-- 2023/puzzles/day25/index.html | 4 ++-- 2024/index.html | 4 ++-- 2024/puzzles/day0/index.html | 4 ++-- 2024/puzzles/day01/index.html | 4 ++-- 2024/puzzles/day02/index.html | 4 ++-- 2024/puzzles/day03/index.html | 4 ++-- 2024/puzzles/day04/index.html | 4 ++-- 2024/puzzles/day05/index.html | 4 ++-- 2024/puzzles/day06/index.html | 4 ++-- 2024/puzzles/day07/index.html | 4 ++-- 2024/puzzles/day08/index.html | 4 ++-- 2024/puzzles/day09/index.html | 4 ++-- 2024/puzzles/day10/index.html | 6 +++--- 2024/puzzles/day11/index.html | 6 +++--- 404.html | 4 ++-- assets/js/{a1a15f20.5d2da92b.js => a1a15f20.c7225a78.js} | 2 +- assets/js/{b84e93db.16b2ef16.js => b84e93db.a14062b6.js} | 2 +- .../{runtime~main.9d085ce3.js => runtime~main.c59d6dd7.js} | 2 +- index.html | 4 ++-- introduction/index.html | 4 ++-- puzzles/day1/index.html | 4 ++-- puzzles/day10/index.html | 4 ++-- puzzles/day11/index.html | 4 ++-- puzzles/day12/index.html | 4 ++-- puzzles/day13/index.html | 4 ++-- puzzles/day14/index.html | 4 ++-- puzzles/day15/index.html | 4 ++-- puzzles/day16/index.html | 4 ++-- puzzles/day17/index.html | 4 ++-- puzzles/day18/index.html | 4 ++-- puzzles/day19/index.html | 4 ++-- puzzles/day2/index.html | 4 ++-- puzzles/day20/index.html | 4 ++-- puzzles/day21/index.html | 4 ++-- puzzles/day22/index.html | 4 ++-- puzzles/day23/index.html | 4 ++-- puzzles/day24/index.html | 4 ++-- puzzles/day25/index.html | 4 ++-- puzzles/day3/index.html | 4 ++-- puzzles/day4/index.html | 4 ++-- puzzles/day5/index.html | 4 ++-- puzzles/day6/index.html | 4 ++-- puzzles/day7/index.html | 4 ++-- puzzles/day8/index.html | 4 ++-- puzzles/day9/index.html | 4 ++-- setup/index.html | 4 ++-- 98 files changed, 195 insertions(+), 195 deletions(-) rename assets/js/{a1a15f20.5d2da92b.js => a1a15f20.c7225a78.js} (77%) rename assets/js/{b84e93db.16b2ef16.js => b84e93db.a14062b6.js} (94%) rename assets/js/{runtime~main.9d085ce3.js => runtime~main.c59d6dd7.js} (98%) diff --git a/2021/index.html b/2021/index.html index cb4d4d3c3..3140d5ed3 100644 --- a/2021/index.html +++ b/2021/index.html @@ -5,13 +5,13 @@ Scala Center Advent of Code | Scala Center Advent of Code - +
Skip to main content
Credit to https://github.com/OlegIlyenko/scala-icon

Learn Scala 3

A simpler, safer and more concise version of Scala, the famous object-oriented and functional programming language.

Solve Advent of Code puzzles

Challenge your programming skills by solving Advent of Code puzzles.

Share with the community

Get or give support to the community. Share your solutions with the community.

- + \ No newline at end of file diff --git a/2022/index.html b/2022/index.html index 697376168..a226156ba 100644 --- a/2022/index.html +++ b/2022/index.html @@ -5,13 +5,13 @@ Scala Center Advent of Code | Scala Center Advent of Code - +
Skip to main content
Credit to https://github.com/OlegIlyenko/scala-icon

Learn Scala 3

A simpler, safer and more concise version of Scala, the famous object-oriented and functional programming language.

Solve Advent of Code puzzles

Challenge your programming skills by solving Advent of Code puzzles.

Share with the community

Get or give support to the community. Share your solutions with the community.

- + \ No newline at end of file diff --git a/2022/puzzles/day01/index.html b/2022/puzzles/day01/index.html index 7a5a1d1df..8efa851ca 100644 --- a/2022/puzzles/day01/index.html +++ b/2022/puzzles/day01/index.html @@ -5,14 +5,14 @@ Day 1: Calorie Counting | Scala Center Advent of Code - +
Skip to main content

Day 1: Calorie Counting

by @bishabosha

Puzzle description

https://adventofcode.com/2022/day/1

Solution Summary

First transform the input into a List of Inventory, each Inventory is a list of Int, representing the calorie count of an item in the inventory, this is handled in scanInventories.

Part 1

Given the List of Inventory, we must first find the total calorie count of each inventory.

For a single Inventory, we do this using the sum method on its items property (found in the List class). e.g. inventory.items.sum.

Then use the map method on the List class, to transform each Inventory to its total calorie count with an anonymous function.

Then sort the resulting list of total calorie counts in descending order, this is provided by scala.math.Ordering.Int.reverse.

The maxInventories method handles the above, returning the top n total calorie counts.

For part 1, use maxInventories with n == 1 to create a singleton list of the largest calorie count.

Part 2

As in part 1, construct the list of sorted total calorie counts with maxInventories. But instead, we need the first 3 elements. We then need to sum the resulting list.

Final Code

import scala.math.Ordering

def part1(input: String): Int =
maxInventories(scanInventories(input), 1).head

def part2(input: String): Int =
maxInventories(scanInventories(input), 3).sum

case class Inventory(items: List[Int])

def scanInventories(input: String): List[Inventory] =
val inventories = List.newBuilder[Inventory]
var items = List.newBuilder[Int]
for line <- input.linesIterator do
if line.isEmpty then
inventories += Inventory(items.result())
items = List.newBuilder
else items += line.toInt
inventories.result()

def maxInventories(inventories: List[Inventory], n: Int): List[Int] =
inventories
.map(inventory => inventory.items.sum)
.sorted(using Ordering.Int.reverse)
.take(n)

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2022/puzzles/day02/index.html b/2022/puzzles/day02/index.html index 9e1887842..cfd3f7c03 100644 --- a/2022/puzzles/day02/index.html +++ b/2022/puzzles/day02/index.html @@ -5,13 +5,13 @@ Day 2: Rock Paper Scissors | Scala Center Advent of Code - +
Skip to main content

Day 2: Rock Paper Scissors

by @bishabosha

Puzzle description

https://adventofcode.com/2022/day/2

Final Code

import Position.*

def part1(input: String): Int =
scores(input, pickPosition).sum

def part2(input: String): Int =
scores(input, winLoseOrDraw).sum

enum Position:
case Rock, Paper, Scissors

// two positions after this one, wrapping around
def winsAgainst: Position = fromOrdinal((ordinal + 2) % 3)

// one position after this one, wrapping around
def losesAgainst: Position = fromOrdinal((ordinal + 1) % 3)

end Position

def readCode(opponent: String) = opponent match
case "A" => Rock
case "B" => Paper
case "C" => Scissors

def scores(input: String, strategy: (Position, String) => Position) =
for case s"$x $y" <- input.linesIterator yield
val opponent = readCode(x)
score(opponent, strategy(opponent, y))

def winLoseOrDraw(opponent: Position, code: String): Position = code match
case "X" => opponent.winsAgainst // we need to lose
case "Y" => opponent // we need to tie
case "Z" => opponent.losesAgainst // we need to win

def pickPosition(opponent: Position, code: String): Position = code match
case "X" => Rock
case "Y" => Paper
case "Z" => Scissors

def score(opponent: Position, player: Position): Int =
val pointsOutcome =
if opponent == player then 3 // tie
else if player.winsAgainst == opponent then 6 // win
else 0 // lose

// Rock = 1, Paper = 2, Scissors = 3
val pointsPlay = player.ordinal + 1

pointsPlay + pointsOutcome
end score

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2022/puzzles/day03/index.html b/2022/puzzles/day03/index.html index 04ce15c93..120e859ab 100644 --- a/2022/puzzles/day03/index.html +++ b/2022/puzzles/day03/index.html @@ -5,13 +5,13 @@ Day 3: Rucksack Reorganization | Scala Center Advent of Code - +
Skip to main content

Day 3: Rucksack Reorganization

by @bishabosha

Puzzle description

https://adventofcode.com/2022/day/3

Final Code

def part1(input: String): Int =
val intersections =
for line <- input.linesIterator yield
val (left, right) = line.splitAt(line.length / 2)
(priorities(left) & priorities(right)).head
intersections.sum

def part2(input: String): Int =
val badges =
for case Seq(a, b, c) <- input.linesIterator.grouped(3) yield
(priorities(a) & priorities(b) & priorities(c)).head
badges.sum

def priorities(str: String) = str.foldLeft(Priorities.emptySet)(_ add _)

object Priorities:
opaque type Set = Long // can fit all 52 priorities in a bitset

// encode priorities as a random access lookup
private val lookup =
val arr = new Array[Int](128) // max key is `'z'.toInt == 122`
for (c, i) <- (('a' to 'z') ++ ('A' to 'Z')).zipWithIndex do
arr(c.toInt) = i + 1
IArray.unsafeFromArray(arr)

val emptySet: Set = 0L

extension (priorities: Set)
infix def add(c: Char): Set = priorities | (1L << lookup(c.toInt))
infix def &(that: Set): Set = priorities & that
def head: Int = java.lang.Long.numberOfTrailingZeros(priorities)

end Priorities

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2022/puzzles/day04/index.html b/2022/puzzles/day04/index.html index ba40d2727..0aaa3bfd1 100644 --- a/2022/puzzles/day04/index.html +++ b/2022/puzzles/day04/index.html @@ -5,13 +5,13 @@ Day 4: Camp Cleanup | Scala Center Advent of Code - +
Skip to main content

Day 4: Camp Cleanup

by @bishabosha

Puzzle description

https://adventofcode.com/2022/day/4

Final Code

def part1(input: String): Int =
foldPairs(input, subsumes)

def part2(input: String): Int =
foldPairs(input, overlaps)

def subsumes(x: Int, y: Int)(a: Int, b: Int): Boolean = x <= a && y >= b
def overlaps(x: Int, y: Int)(a: Int, b: Int): Boolean = x <= a && y >= a || x <= b && y >= b

def foldPairs(input: String, hasOverlap: (Int, Int) => (Int, Int) => Boolean): Int =
val matches =
for line <- input.linesIterator yield
val Array(x,y,a,b) = line.split("[,-]").map(_.toInt): @unchecked
hasOverlap(x,y)(a,b) || hasOverlap(a,b)(x,y)
matches.count(identity)

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2022/puzzles/day05/index.html b/2022/puzzles/day05/index.html index d7ab09e32..1c9d298f0 100644 --- a/2022/puzzles/day05/index.html +++ b/2022/puzzles/day05/index.html @@ -5,13 +5,13 @@ Day 5: Supply Stacks | Scala Center Advent of Code - +
Skip to main content

Day 5: Supply Stacks

by @bishabosha

Puzzle description

https://adventofcode.com/2022/day/5

Final Code

def part1(input: String): String =
moveAllCrates(input, _ reverse_::: _) // concat in reverse order

def part2(input: String): String =
moveAllCrates(input, _ ::: _) // concat in normal order

/** each column is 4 chars wide (or 3 if terminal) */
def parseRow(row: String) =
for i <- 0 to row.length by 4 yield
if row(i) == '[' then
row(i + 1) // the crate id
else
'#' // empty slot

def parseColumns(header: IndexedSeq[String]): IndexedSeq[List[Char]] =
val crates :+ colsStr = header: @unchecked
val columns = colsStr.split(" ").filter(_.nonEmpty).length

val rows = crates.map(parseRow(_).padTo(columns, '#')) // pad empty slots at the end

// transpose the rows to get the columns, then remove the terminal empty slots from each column
rows.transpose.map(_.toList.filterNot(_ == '#'))
end parseColumns

def moveAllCrates(input: String, moveCrates: (List[Char], List[Char]) => List[Char]): String =
val (headerLines, rest0) = input.linesIterator.span(_.nonEmpty)
val instructions = rest0.drop(1) // drop the empty line after the header

def move(cols: IndexedSeq[List[Char]], n: Int, idxA: Int, idxB: Int) =
val (toMove, aRest) = cols(idxA).splitAt(n)
val b2 = moveCrates(toMove, cols(idxB))
cols.updated(idxA, aRest).updated(idxB, b2)

val columns = parseColumns(headerLines.to(IndexedSeq))

val columns1 = instructions.foldLeft(columns) { case (columns, s"move $n from $a to $b") =>
move(columns, n.toInt, a.toInt - 1, b.toInt - 1)
}
columns1.map(_.head).mkString
end moveAllCrates

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2022/puzzles/day06/index.html b/2022/puzzles/day06/index.html index bb2d726b7..476db8a1d 100644 --- a/2022/puzzles/day06/index.html +++ b/2022/puzzles/day06/index.html @@ -5,7 +5,7 @@ Day 6: Tuning Trouble | Scala Center Advent of Code - + @@ -21,7 +21,7 @@ the multiset described above, you only care about the first and last element of each window, which can be represented by two indexes into the string.

The final optimisation is to only update the set when the last element of the window is different to the first element of the previous window.

The final optimised code is presented below, including an implementation of the multiset:

def part1(input: String): Int =
findIndexOptimal(input, n = 4)

def part2(input: String): Int =
findIndexOptimal(input, n = 14)

class MultiSet:
private val counts = new Array[Int](26)
private var uniqueElems = 0

def size = uniqueElems

def add(c: Char) =
val count = counts(c - 'a')
if count == 0 then
uniqueElems += 1
counts(c - 'a') += 1

def remove(c: Char) =
val count = counts(c - 'a')
if count > 0 then
if count == 1 then
uniqueElems -= 1
counts(c - 'a') -= 1
end MultiSet

def findIndexOptimal(input: String, n: Int): Int =
val counts = MultiSet()
def loop(i: Int, j: Int): Int =
if counts.size == n then
i + n // found the index
else if j >= input.length then
-1 // window went beyond the end
else
val previous = input(i)
val last = input(j)
if previous != last then
counts.remove(previous)
counts.add(last)
loop(i = i + 1, j = j + 1)
end loop
input.iterator.take(n).foreach(counts.add) // add up-to the first `n` elements
loop(i = 0, j = n)

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2022/puzzles/day07/index.html b/2022/puzzles/day07/index.html index c2897bb79..c0a7a077c 100644 --- a/2022/puzzles/day07/index.html +++ b/2022/puzzles/day07/index.html @@ -5,13 +5,13 @@ Day 7: No Space Left On Device | Scala Center Advent of Code - +
Skip to main content

Day 7: No Space Left On Device

code by Jan Boerman

Puzzle description

https://adventofcode.com/2022/day/7

Solution

First of all, we need to create types for commands, to differentiate the input:

enum Command:
case ChangeDirectory(directory: String)
case ListFiles

enum TerminalOutput:
case Cmd(cmd: Command)
case Directory(name: String)
case File(size: Int, name: String)

Let's make a directory structure, in which we will define files as mutable.Map, that can contain name (String) and size (Integer), will have reference to parent directory, and will be able to contain subdirectories:

class DirectoryStructure(val name: String,
val subDirectories: mutable.Map[String, DirectoryStructure],
val files: mutable.Map[String, Int],
val parent: DirectoryStructure | Null)

And now we need to come up with a way to parse out input code:

def input (str: String) = str.linesIterator.map {
case s"$$ cd $directory" => Cmd(ChangeDirectory(directory))
case s"$$ ls" => Cmd(ListFiles)
case s"dir $directory" => Directory(directory)
case s"$size $file" => File(size.toInt, file)
}.toList

We have to come up with a way to calculate directory size -- we can use sum for the size of all files in directory and define size of all of the following subdirectories recursively, which will take care of problem:

def directorySize(dir: DirectoryStructure): Int =
dir.files.values.sum + dir.subDirectories.values.map(directorySize).sum

Now we need to create a function to build the directory structure from the input. For that we can use match and separate input, -- for that we can use cases and recursion will do the rest for us:

def buildState(input: List[TerminalOutput], currentDir: DirectoryStructure | Null, rootDir: DirectoryStructure): Unit = input match
case Cmd(ChangeDirectory("/")) :: t => buildState(t, rootDir, rootDir)
case Cmd(ChangeDirectory("..")) :: t => buildState(t, currentDir.parent, rootDir)
case Cmd(ChangeDirectory(name)) :: t => buildState(t, currentDir.subDirectories(name), rootDir)
case Cmd(ListFiles) :: t => buildState(t, currentDir, rootDir)
case File(size, name) :: t =>
currentDir.files.put(name, size)
buildState(t, currentDir, rootDir)
case Directory(name) :: t =>
currentDir.subDirectories.put(name, DirectoryStructure(name, mutable.Map.empty, mutable.Map.empty, currentDir))
buildState(t, currentDir, rootDir)
case Nil => ()

And now, we need to assemble the program, in part one, we will search for all directories with size smaller 100000, and calculate the sum of their sizes.

def part1(output: String): Int =
val rootDir = buildData(output)
collectSizes(rootDir, _ < 100000).sum

In part two, we are looking for the smallest directory, which size is big enough to free up enough space on the filesystem to install update (30,000,00). We have to find out how much space is required for update, considering our available unused space:

def part2(output: String): Int =
val rootDir = buildData(output)
val totalUsed = directorySize(rootDir)
val totalUnused = 70_000_000 - totalUsed
val required = 30_000_000 - totalUnused
collectSizes(rootDir, _ >= required).min

Final Code

import scala.annotation.tailrec
import scala.collection.mutable

import TerminalOutput.*
import Command.*

def input (str: String) = str.linesIterator.map {
case s"$$ cd $directory" => Cmd(ChangeDirectory(directory))
case s"$$ ls" => Cmd(ListFiles)
case s"dir $directory" => Directory(directory)
case s"$size $file" => File(size.toInt, file)
}.toList

enum Command:
case ChangeDirectory(directory: String)
case ListFiles

enum TerminalOutput:
case Cmd(cmd: Command)
case Directory(name: String)
case File(size: Int, name: String)

class DirectoryStructure(val name: String,
val subDirectories: mutable.Map[String, DirectoryStructure],
val files: mutable.Map[String, Int],
val parent: DirectoryStructure | Null)

def buildState(input: List[TerminalOutput], currentDir: DirectoryStructure | Null, rootDir: DirectoryStructure): Unit = input match
case Cmd(ChangeDirectory("/")) :: t => buildState(t, rootDir, rootDir)
case Cmd(ChangeDirectory("..")) :: t => buildState(t, currentDir.parent, rootDir)
case Cmd(ChangeDirectory(name)) :: t => buildState(t, currentDir.subDirectories(name), rootDir)
case Cmd(ListFiles) :: t => buildState(t, currentDir, rootDir)
case File(size, name) :: t =>
currentDir.files.put(name, size)
buildState(t, currentDir, rootDir)
case Directory(name) :: t =>
currentDir.subDirectories.put(name, DirectoryStructure(name, mutable.Map.empty, mutable.Map.empty, currentDir))
buildState(t, currentDir, rootDir)
case Nil => ()

def directorySize(dir: DirectoryStructure): Int =
dir.files.values.sum + dir.subDirectories.values.map(directorySize).sum

def collectSizes(dir: DirectoryStructure, criterion: Int => Boolean): Iterable[Int] =
val mySize = directorySize(dir)
val children = dir.subDirectories.values.flatMap(collectSizes(_, criterion))
if criterion(mySize) then mySize :: children.toList else children

def buildData(output: String) =
val rootDir = new DirectoryStructure("/", mutable.Map.empty, mutable.Map.empty, null)
buildState(input(output), null, rootDir)
rootDir


def part1(output: String): Int =
val rootDir = buildData(output)
collectSizes(rootDir, _ < 100000).sum

def part2(output: String): Int =
val rootDir = buildData(output)
val totalUsed = directorySize(rootDir)
val totalUnused = 70_000_000 - totalUsed
val required = 30_000_000 - totalUnused
collectSizes(rootDir, _ >= required).min

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2022/puzzles/day08/index.html b/2022/puzzles/day08/index.html index 396aeeead..9672329a1 100644 --- a/2022/puzzles/day08/index.html +++ b/2022/puzzles/day08/index.html @@ -5,7 +5,7 @@ Day 8: Treetop Tree House | Scala Center Advent of Code - + @@ -28,7 +28,7 @@ For example trees of height 3 can see lengths(3) trees. And we update this list with each new tree we see, if it's x big, all trees at least x small will only see that tree, and all other trees will see one more: at index i of value v: if i <= x then 1 else v+1.

We can then use this in a similar way to what we did with max and rollingMax before:

val rollingLengths = line.scanRight( List.fill(10)(0) ){
case (curr, lengths) =>
lengths.zipWithIndex.map{ case (v, i) => if i <= curr then 1 else v+1 }
}.init

We then get the score by reading lengths at the appropriate point, again as was done with rollingMax:

rollingLengths.zip(line).map{ case (lengths, curr) => lengths(curr) }

By combining everything, noticing once again our calculation is the same for each line, we get:

def computeScore(ls: HeightField): ScoreField = ls.map{ line =>
val rollingLengths = line.scanRight( List.fill(10)(0) ){
case (curr, lengths) =>
lengths.zipWithIndex.map{ case (v, i) => if i <= curr then 1 else v+1 }
}.init
rollingLengths.zip(line).map{ case (lengths, curr) => lengths(curr) }
}

Where ScoreField is identical to HeightField, but serves to make the code more readable:

type ScoreField = Field[Int]

We can use the same trick as before to get all the other directions for free:

val scoreFields: List[ScoreField] = computeInAllDirections(parsed, computeScore)

This time instead of or-ing, we need to multiply "A tree's scenic score is found by multiplying together its viewing distance in each of the four directions.":

val scoreField: ScoreField = scoreFields.reduce(combine(_ * _))

And this time the last step is to get the heighest value instead of the sum:

scoreField.megaReduce(_ max _)

Final Code

def part1(input: String): Int =
val parsed = parse(input)
val visibilityFields: List[VisibilityField] = computeInAllDirections(parsed, computeVisibility)
val visibilityField: VisibilityField = visibilityFields.reduce(combine(_ | _))
visibilityField.megaMap(if _ then 1 else 0).megaReduce(_ + _)

def part2(input: String): Int =
val parsed = parse(input)
val scoreFields: List[ScoreField] = computeInAllDirections(parsed, computeScore)
val scoreField: ScoreField = scoreFields.reduce(combine(_ * _))
scoreField.megaReduce(_ max _)

type Field[A] = List[List[A]]

extension [A](xss: Field[A])
def megaZip[B](yss: Field[B]): Field[(A, B)] = (xss zip yss).map( (xs, ys) => xs zip ys )
def megaMap[B](f: A => B): Field[B] = xss.map(_.map(f))
def megaReduce(f: (A,A) => A): A = xss.map(_.reduce(f)).reduce(f)

def combine[A](op: ((A,A)) => A)(f1: Field[A], f2: Field[A]): Field[A] = f1.megaZip(f2).megaMap(op)

def computeInAllDirections[A, B](xss: Field[A], f: Field[A] => Field[B]): List[Field[B]] =
for
transpose <- List(false, true)
reverse <- List(false, true)
yield
val t = if transpose then xss.transpose else xss
val in = if reverse then t.map(_.reverse) else t
val res = f(in)
val r = if reverse then res.map(_.reverse) else res
val out = if transpose then r.transpose else r
out

type HeightField = Field[Int]
type ScoreField = Field[Int]

type VisibilityField = Field[Boolean]

def parse(input: String): HeightField = input.split('\n').toList.map(line => line.map(char => char.asDigit).toList)

def computeVisibility(ls: HeightField): VisibilityField = ls.map{ line =>
val rollingMax = line.scanLeft(-1){ case (max, curr) => Math.max(max, curr) }.init
rollingMax.zip(line).map{ case (max, curr) => max < curr) }
}

def computeScore(ls: HeightField): ScoreField = ls.map{ line =>
val rollingLengths = line.scanRight( List.fill(10)(0) ){
case (curr, lengths) =>
lengths.zipWithIndex.map{ case (v, i) => if i <= curr then 1 else v+1 }
}.init
rollingLengths.zip(line).map{ case (lengths, curr) => lengths(curr) }
}

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2022/puzzles/day09/index.html b/2022/puzzles/day09/index.html index 5729e1459..ace4c5e98 100644 --- a/2022/puzzles/day09/index.html +++ b/2022/puzzles/day09/index.html @@ -5,7 +5,7 @@ Day 9: Rope Bridge | Scala Center Advent of Code - + @@ -27,7 +27,7 @@ Each line you can extract the direction and steps count with a pattern binding val (s"$dir $n") = line, then use Direction.valueOf to lookup the direction, and .toInt to convert n to the number of steps.

Then to run n steps, create the steps iterator, then drop n elements to advance the state n steps, then take the next() element:

def uniquePositions(input: String, knots: Int): Int =
val end = input.linesIterator.foldLeft(initialState(knots)) { case (state, line) =>
val (s"$dir $n") = line: @unchecked
steps(state, Direction.valueOf(dir)).drop(n.toInt).next()
}
end.uniques.size

Part 1 needs 2 knots, and part 2 needs 10 knots, they can be implemented as such:

def part1(input: String): Int =
uniquePositions(input, knots = 2)

def part2(input: String): Int =
uniquePositions(input, knots = 10)

Final Code

import Direction.*

def part1(input: String): Int =
uniquePositions(input, knots = 2)

def part2(input: String): Int =
uniquePositions(input, knots = 10)

case class Position(x: Int, y: Int):
def moveOne(dir: Direction): Position = dir match
case U => Position(x, y + 1)
case D => Position(x, y - 1)
case L => Position(x - 1, y)
case R => Position(x + 1, y)

def follow(head: Position): Position =
val dx = head.x - x
val dy = head.y - y
if dx.abs > 1 || dy.abs > 1 then Position(x + dx.sign, y + dy.sign) // follow the head
else this // stay put

case class State(uniques: Set[Position], head: Position, knots: List[Position])

enum Direction:
case U, D, L, R

def followAll(head: Position, knots: List[Position]) =
var prev = head // head was already moved with `moveOne`
val buf = List.newBuilder[Position]
for knot <- knots do
val next = knot.follow(prev)
buf += next
prev = next
(prev, buf.result())
end followAll

def step(dir: Direction, state: State) =
val head1 = state.head.moveOne(dir)
val (last, knots1) = followAll(head1, state.knots)
State(state.uniques + last, head1, knots1)

def steps(state: State, dir: Direction): Iterator[State] =
Iterator.iterate(state)(state => step(dir, state))

def initialState(knots: Int) =
val zero = Position(0, 0)
State(Set(zero), zero, List.fill(knots - 1)(zero))

def uniquePositions(input: String, knots: Int): Int =
val end = input.linesIterator.foldLeft(initialState(knots)) { case (state, line) =>
val (s"$dir $n") = line: @unchecked
steps(state, Direction.valueOf(dir)).drop(n.toInt).next()
}
end.uniques.size

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2022/puzzles/day10/index.html b/2022/puzzles/day10/index.html index a87685712..abe619701 100644 --- a/2022/puzzles/day10/index.html +++ b/2022/puzzles/day10/index.html @@ -5,14 +5,14 @@ Day 10: Cathode-Ray Tube | Scala Center Advent of Code - +
Skip to main content

Day 10: Cathode-Ray Tube

code and article by Mewen Crespo (reviewed by Jamie Thompson)

Puzzle description

https://adventofcode.com/2022/day/10

Solution

Today's goal is to simulate the register's values over time. Once this is done, the rest falls in place rather quickly. From the puzzle description, we know there are two commands availaible: noop and addx. This can be implemented with a enum:

enum Command:
case Noop
case Addx(x: Int)

Now, we need to parse this commands from the string. This can be done using a for loop to match each line of the input:

import Command.*

def commandsIterator(input: String): Iterator[Command] =
for line <- input.linesIterator yield line match
case "noop" => Noop
case s"addx $x" if x.toIntOption.isDefined => Addx(x.toInt)
case _ => throw IllegalArgumentException(s"Invalid command '$line''")

Here you can use linesIterator to retrieve the lines (it returns an Iterator[String]) and mapped every line using a for .. yield comprehension with a match body. Note the use of the string interpolator s for a simple way to parse strings.

tip

Error checking: Althought not necessary in this puzzle, it is a good practice to check the validity of the input. Here, we checked that the string matched with $x is a valid integer string before entering the second case and throw an exception if none of the first cases were matched.

Now we are ready to compute the registers values. We choose to implement it as an Iterator[Int] which will return the register's value each cycle at a time. For this, we need to loop throught the commands. If the command is a noop, then the next cycle will have the same value. If the command is a addx x then the next cycle will be the same value and the cycle afterward will be x more. There is an issue here: the addx command generates two cycles whereas the noop command generates only one.

To circumvent this issue, generate an Iterator[List[Int]] first which will be flattened afterwards. The first iterator is constructed using the scanLeft method to yield the following code:

val RegisterStartValue = 1

def registerValuesIterator(input: String): Iterator[Int] =
val steps = commandsIterator(input).scanLeft(RegisterStartValue :: Nil) { (values, cmd) =>
val value = values.last
cmd match
case Noop => value :: Nil
case Addx(x) => value :: value + x :: Nil
}
steps.flatten

Notice that at each step we call .last on the accumulated List[Int] value which, in this case, is the register's value at the start of the last cycle.

Part 1

In the first part, the challenge asks you to compute the strength at the 20th cycle and then every 40th cycle. This can be done using a combination of drop (to skip the first 19 cycles), grouped (to group the cycles by 40) and map(_.head) (to only take the first cycle of each group of 40). The computation of the strengths is, on the other hand, done using the zipWithIndex method and a for ... yield comprehension. This leads to the following code:

def registerStrengthsIterator(input: String): Iterator[Int] =
val it = for (reg, i) <- registerValuesIterator(input).zipWithIndex yield (i + 1) * reg
it.drop(19).grouped(40).map(_.head)

The result of Part 1 is the sum of this iterator:

def part1(input: String): Int = registerStrengthsIterator(input).sum

Part 2

In the second part, we are asked to draw a CRT output. As stated in the puzzle description, the register is interpreted as the position of a the sprite ###. The CRT iterates throught each line and, if the sprites touches the touches the current position, draws a #. Otherwise the CRT draws a .. The register's cycles are stepped in synced with the CRT.

First, the CRT's position is just the cycle's index modulo the CRT's width (40 in our puzzle). Then, the CRT draw the sprite if and only if the register's value is the CRT's position, one more or one less. In other words, if (reg_value - (cycle_id % 40)).abs <= 1. Using the zipWithIndex method to obtain the cycles' indexes we end up with the following code:

val CRTWidth: Int = 40

def CRTCharIterator(input: String): Iterator[Char] =
for (reg, crtPos) <- registerValuesIterator(input).zipWithIndex yield
if (reg - (crtPos % CRTWidth)).abs <= 1 then
'#'
else
'.'

Now, concatenate the chars and add new lines at the required places. This is done using the mkString methods:

def part2(input: String): String =
CRTCharIterator(input).grouped(CRTWidth).map(_.mkString).mkString("\n")

Final Code

import Command.*

def part1(input: String): Int =
registerStrengthsIterator(input).sum

def part2(input: String): String =
CRTCharIterator(input).grouped(CRTWidth).map(_.mkString).mkString("\n")

enum Command:
case Noop
case Addx(x: Int)

def commandsIterator(input: String): Iterator[Command] =
for line <- input.linesIterator yield line match
case "noop" => Noop
case s"addx $x" if x.toIntOption.isDefined => Addx(x.toInt)
case _ => throw IllegalArgumentException(s"Invalid command '$line''")

val RegisterStartValue = 1

def registerValuesIterator(input: String): Iterator[Int] =
val steps = commandsIterator(input).scanLeft(RegisterStartValue :: Nil) { (values, cmd) =>
val value = values.last
cmd match
case Noop => value :: Nil
case Addx(x) => value :: value + x :: Nil
}
steps.flatten

def registerStrengthsIterator(input: String): Iterator[Int] =
val it = for (reg, i) <- registerValuesIterator(input).zipWithIndex yield (i + 1) * reg
it.drop(19).grouped(40).map(_.head)

val CRTWidth: Int = 40

def CRTCharIterator(input: String): Iterator[Char] =
for (reg, crtPos) <- registerValuesIterator(input).zipWithIndex yield
if (reg - (crtPos % CRTWidth)).abs <= 1 then
'#'
else
'.'

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2022/puzzles/day11/index.html b/2022/puzzles/day11/index.html index 29740256e..760f1f402 100644 --- a/2022/puzzles/day11/index.html +++ b/2022/puzzles/day11/index.html @@ -5,13 +5,13 @@ Day 11: Monkey in the Middle | Scala Center Advent of Code - +
Skip to main content

Day 11: Monkey in the Middle

Puzzle description

https://adventofcode.com/2022/day/11

Final Code

import scala.collection.immutable.Queue

def part1(input: String): Long =
run(initial = parseInput(input), times = 20, adjust = _ / 3)

def part2(input: String): Long =
run(initial = parseInput(input), times = 10_000, adjust = identity)

type Worry = Long
type Op = Worry => Worry
type Monkeys = IndexedSeq[Monkey]

case class Monkey(
items: Queue[Worry],
divisibleBy: Int,
ifTrue: Int,
ifFalse: Int,
op: Op,
inspected: Int
)

def iterate[Z](times: Int)(op: Z => Z)(z: Z): Z =
(0 until times).foldLeft(z) { (z, _) => op(z) }

def run(initial: Monkeys, times: Int, adjust: Op): Long =
val lcm = initial.map(_.divisibleBy.toLong).product
val monkeys = iterate(times)(round(adjust, lcm))(initial)
monkeys.map(_.inspected.toLong).sorted.reverseIterator.take(2).product

def round(adjust: Op, lcm: Worry)(monkeys: Monkeys): Monkeys =
monkeys.indices.foldLeft(monkeys) { (monkeys, index) =>
turn(index, monkeys, adjust, lcm)
}

def turn(index: Int, monkeys: Monkeys, adjust: Op, lcm: Worry): Monkeys =
val monkey = monkeys(index)
val Monkey(items, divisibleBy, ifTrue, ifFalse, op, inspected) = monkey

val monkeys1 = items.foldLeft(monkeys) { (monkeys, item) =>
val inspected = op(item)
val nextWorry = adjust(inspected) % lcm
val thrownTo =
if nextWorry % divisibleBy == 0 then ifTrue
else ifFalse
val thrownToMonkey =
val m = monkeys(thrownTo)
m.copy(items = m.items :+ nextWorry)
monkeys.updated(thrownTo, thrownToMonkey)
}
val monkey1 = monkey.copy(
items = Queue.empty,
inspected = inspected + items.size
)
monkeys1.updated(index, monkey1)
end turn

def parseInput(input: String): Monkeys =

def eval(by: String): Op =
if by == "old" then identity
else Function.const(by.toInt)

def parseOperator(op: String, left: Op, right: Op): Op =
op match
case "+" => old => left(old) + right(old)
case "*" => old => left(old) * right(old)

IArray.from(
for
case Seq(
s"Monkey $n:",
s" Starting items: $items",
s" Operation: new = $left $operator $right",
s" Test: divisible by $div",
s" If true: throw to monkey $ifTrue",
s" If false: throw to monkey $ifFalse",
_*
) <- input.linesIterator.grouped(7)
yield
val op = parseOperator(operator, eval(left), eval(right))
val itemsQueue = items.split(", ").map(_.toLong).to(Queue)
Monkey(itemsQueue, div.toInt, ifTrue.toInt, ifFalse.toInt, op, inspected = 0)
)
end parseInput

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2022/puzzles/day12/index.html b/2022/puzzles/day12/index.html index 8534fcc1c..5b8a86899 100644 --- a/2022/puzzles/day12/index.html +++ b/2022/puzzles/day12/index.html @@ -5,13 +5,13 @@ Day 12: Hill Climbing Algorithm | Scala Center Advent of Code - +
Skip to main content

Day 12: Hill Climbing Algorithm

Puzzle description

https://adventofcode.com/2022/day/12

Solution

Today's challenge is to simulate the breadth-first search over a graph. First, let's create a standard Point class and define addition on it:

case class Point(x: Int, y: Int):
def move(dx: Int, dy: Int):
Point = Point(x + dx, y + dy)
override def toString: String =
s"($x, $y)"
end Point

Now we need a representation that will serve as a substitute for moves:

val up    = (0, 1)
val down = (0, -1)
val left = (-1, 0)
val right = (1, 0)
val possibleMoves = List(up, down, left, right)

Let's make a path function that will help us to calculate the length of our path to the point, based on our moves, that we defined before:

def path(point: Point, net: Map[Point, Char]): Seq[Point] =
possibleMoves.map(point.move).filter(net.contains)

A function that fulfills our need to match an entry with the point we are searching for:

def matching(point: Point, net: Map[Point, Char]): Char =
net(point) match
case 'S' => 'a'
case 'E' => 'z'
case other => other

Now we just need to put the program together. First of all, let's map out our indices to the source, so we can create a queue for path representation. After that we need to create a map, to keep track the length of our path. For that we will need to map E entry to zero. The last part is the implementation of bfs on a Queue.

def solution(source: IndexedSeq[String], srchChar: Char): Int =
// create a sequence of Point objects and their corresponding character in source
val points =
for
y <- source.indices
x <- source.head.indices
yield
Point(x, y) -> source(y)(x)
val p = points.toMap
val initial = p.map(_.swap)('E')
val queue = collection.mutable.Queue(initial)
val length = collection.mutable.Map(initial -> 0)
//bfs
while queue.nonEmpty do
val visited = queue.dequeue()
if p(visited) == srchChar then
return length(visited)
for visited1 <- path(visited, p) do
val shouldAdd =
!length.contains(visited1)
&& matching(visited, p) - matching(visited1, p) <= 1
if shouldAdd then
queue.enqueue(visited1)
length(visited1) = length(visited) + 1
end for
end while
throw IllegalStateException("unexpected end of search area")
end solution

In part one srchChar is 'S', but since our method in non-exhaustive, we may apply the same function for 'a'

def part1(data: String): Int =
solution(IndexedSeq.from(data.linesIterator), 'S')
def part2(data: String): Int =
solution(IndexedSeq.from(data.linesIterator), 'a')

And that's it!

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2022/puzzles/day13/index.html b/2022/puzzles/day13/index.html index be1dd753d..dc607fa09 100644 --- a/2022/puzzles/day13/index.html +++ b/2022/puzzles/day13/index.html @@ -5,14 +5,14 @@ Day 13: Distress Signal | Scala Center Advent of Code - +
Skip to main content

Day 13: Distress Signal

by Jamie Thompson

Puzzle description

https://adventofcode.com/2022/day/13

Final Code

import scala.collection.immutable.Queue
import scala.math.Ordered.given
import Packet.*

def part1(input: String): Int =
findOrderedIndices(input)

def part2(input: String): Int =
findDividerIndices(input)

def findOrderedIndices(input: String): Int =
val indices = (
for
case (Seq(a, b, _*), i) <- input.linesIterator.grouped(3).zipWithIndex
if readPacket(a) <= readPacket(b)
yield
i + 1
)
indices.sum

def findDividerIndices(input: String): Int =
val dividers = List("[[2]]", "[[6]]").map(readPacket)
val lookup = dividers.toSet
val packets = input
.linesIterator
.filter(_.nonEmpty)
.map(readPacket)
val indices = (dividers ++ packets)
.sorted
.iterator
.zipWithIndex
.collect { case (p, i) if lookup.contains(p) => i + 1 }
indices.take(2).product

enum Packet:
case Nested(packets: List[Packet])
case Num(value: Int)

case class State(number: Int, values: Queue[Packet]):
def nextWithDigit(digit: Int): State = // add digit to number
copy(number = if number == -1 then digit else number * 10 + digit)

def nextWithNumber: State =
if number == -1 then this // no number to commit
else
// reset number, add accumulated number to values
State.empty.copy(values = values :+ Num(number))

object State:
val empty = State(-1, Queue.empty)

def readPacket(input: String): Packet =
def loop(i: Int, state: State, stack: List[Queue[Packet]]): Packet =
input(i) match // assume that list is well-formed.
case '[' =>
loop(i + 1, State.empty, state.values :: stack) // push old state to stack
case ']' => // add trailing number, close packet
val packet = Nested(state.nextWithNumber.values.toList)
stack match
case values1 :: rest => // restore old state
loop(i + 1, State.empty.copy(values = values1 :+ packet), rest)
case Nil => // terminating case
packet
case ',' => loop(i + 1, state.nextWithNumber, stack)
case n => loop(i + 1, state.nextWithDigit(n.asDigit), stack)
end loop
if input.nonEmpty && input(0) == '[' then
loop(i = 1, State.empty, stack = Nil)
else
throw IllegalArgumentException(s"Invalid input: `$input`")
end readPacket

given PacketOrdering: Ordering[Packet] with

def nestedCompare(ls: List[Packet], rs: List[Packet]): Int = (ls, rs) match
case (l :: ls1, r :: rs1) =>
val res = compare(l, r)
if res == 0 then nestedCompare(ls1, rs1) // equal, look at next element
else res // less or greater

case (_ :: _, Nil) => 1 // right ran out of elements first
case (Nil, _ :: _) => -1 // left ran out of elements first
case (Nil, Nil) => 0 // equal size
end nestedCompare

def compare(left: Packet, right: Packet): Int = (left, right) match
case (Num(l), Num(r)) => l compare r
case (Nested(l), Nested(r)) => nestedCompare(l, r)
case (num @ Num(_), Nested(r)) => nestedCompare(num :: Nil, r)
case (Nested(l), num @ Num(_)) => nestedCompare(l, num :: Nil)
end compare

end PacketOrdering

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

- + \ No newline at end of file diff --git a/2022/puzzles/day14/index.html b/2022/puzzles/day14/index.html index f3250d1bf..3f57aac31 100644 --- a/2022/puzzles/day14/index.html +++ b/2022/puzzles/day14/index.html @@ -5,14 +5,14 @@ Day 14: Regolith Reservoir | Scala Center Advent of Code - +
Skip to main content

Day 14: Regolith Reservoir

Puzzle description

https://adventofcode.com/2022/day/14

Final Solution

def part1(input: String): Int =
val search = parseInput(input)
search.states
.takeWhile(_.fallingPath.head.y < search.lowestRock)
.last
.sand
.size

def part2(input: String): Int =
parseInput(input).states.last.sand.size

def parseInput(input: String): Scan =
val paths = input.linesIterator
.map { line =>
line.split(" -> ").map { case s"$x,$y" => Point(x.toInt, y.toInt) }.toList
}
val rocks = paths.flatMap { path =>
path.sliding(2).flatMap {
case List(p1, p2) =>
val dx = p2.x - p1.x
val dy = p2.y - p1.y

if dx == 0 then (p1.y to p2.y by dy.sign).map(Point(p1.x, _))
else (p1.x to p2.x by dx.sign).map(Point(_, p1.y))
case _ => None
}
}.toSet
Scan(rocks)

case class Point(x: Int, y: Int)

case class Scan(rocks: Set[Point]):
val lowestRock = rocks.map(_.y).max
val floor = lowestRock + 2

case class State(fallingPath: List[Point], sand: Set[Point]):
def isFree(p: Point) = !sand(p) && !rocks(p)

def next: Option[State] = fallingPath.headOption.map {
case sandUnit @ Point(x, y) =>
val down = Some(Point(x, y + 1)).filter(isFree)
val downLeft = Some(Point(x - 1, y + 1)).filter(isFree)
val downRight = Some(Point(x + 1, y + 1)).filter(isFree)

down.orElse(downLeft).orElse(downRight).filter(_.y < floor) match
case Some(fallingPos) =>
State(fallingPos :: fallingPath, sand)
case None =>
State(fallingPath.tail, sand + sandUnit)
}

def states: LazyList[State] =
val source = Point(500, 0)
LazyList.unfold(State(List(source), Set.empty)) { _.next.map(s => s -> s) }
end Scan

Solutions from the community

Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

- + \ No newline at end of file diff --git a/2022/puzzles/day15/index.html b/2022/puzzles/day15/index.html index 345a14a79..c5c203814 100644 --- a/2022/puzzles/day15/index.html +++ b/2022/puzzles/day15/index.html @@ -5,7 +5,7 @@ Day 15: Beacon Exclusion Zone | Scala Center Advent of Code - + @@ -13,7 +13,7 @@
Skip to main content

Day 15: Beacon Exclusion Zone

Puzzle description

https://adventofcode.com/2022/day/15

Explanation

Part 1

We first model and parse the input:

case class Position(x: Int, y: Int)

def parse(input: String): List[(Position, Position)] =
input.split("\n").toList.map{
case s"Sensor at x=$sx, y=$sy: closest beacon is at x=$bx, y=$by" =>
(Position(sx.toInt, sy.toInt), Position(bx.toInt, by.toInt))
}

We then model the problem-specific knowledge:

def distance(p1: Position, p2: Position): Int =
Math.abs(p1.x - p2.x) + Math.abs(p1.y - p2.y)

def distanceToLine(p: Position, y: Int): Int =
Math.abs(p.y - y)

We use it to compute how much of a line is covered by one (by lineCoverage) and all (by coverOfLine) sensors:

def lineCoverage(sensor: Position, radius: Int, lineY: Int): Range =
val radiusInLine = radius - distanceToLine(sensor, lineY)

// if radiusInLine is smaller than 0, the range will be empty
(sensor.x - radiusInLine) to (sensor.x + radiusInLine)

def coverOfLine(sensorsWithDistances: List[(Position, Int)], line: Int) =
sensorsWithDistances.map( (sensor, radius) => lineCoverage(sensor, radius, line) ).filter(_.nonEmpty)

This is enought to solve part one:

def part1(input: String): Int =
val parsed: List[(Position, Position)] = parse(input)
val beacons: Set[Position] = parsed.map(_._2).toSet
val sensorsWithDistances: List[(Position, Int)] =
parsed.map( (sensor, beacon) => (sensor, distance(sensor, beacon)) )

val line = 2000000
val cover: List[Range] = coverOfLine(sensorsWithDistances, line)
val beaconsOnLine: Set[Position] = beacons.filter(_.y == line)
val count: Int = cover.map(_.size).sum - beaconsOnLine.size
count

Part 2

We wish to remove ranges from other ranges, sadly there is no built-in method to do so, instead rellying on a cast to a collection, which makes computation much much slower. Therefore we define our own difference method which returns zero, one or two ranges:

def smartDiff(r1: Range, r2: Range): List[Range] =
val innit = r1.start to Math.min(r2.start - 1, r1.last)
val tail = Math.max(r1.start, r2.last + 1) to r1.last
val res = if innit == tail then
List(innit)
else
List(innit, tail)
res.filter(_.nonEmpty).toList

This allows us to subtract the cover from our target interval like so:

def remainingSpots(target: Range, cover: List[Range]): Set[Int] =

def rec(partialTarget: List[Range], remainingCover: List[Range]): List[Range] =
if remainingCover.isEmpty then
partialTarget
else
val (curr: Range) :: rest = remainingCover: @unchecked
rec(
partialTarget = partialTarget.flatMap( r => smartDiff(r, curr) ),
remainingCover = rest
)

rec(List(target), cover).flatten.toSet

We can then iterate through all lines, and computing for each which positions are free. As per the problem statement, we know there will only be one inside the square of side 0 to 4_000_000. We then compute the solution's tuning frequency.

def part2(input: String): Any =

val parsed: List[(Position, Position)] = parse(input)
val beacons: Set[Position] = parsed.map(_._2).toSet
val sensorsWithDistances: List[(Position, Int)] =
parsed.map( (sensor, beacon) => (sensor, distance(sensor, beacon)) )

val target: Range = 0 to 4_000_000
val spots: Seq[Position] = target.flatMap{
line =>
val cover: List[Range] = coverOfLine(sensorsWithDistances, line)
val beaconsOnLine: Set[Position] = beacons.filter(_.y == line)

val remainingRanges: List[Range] = cover.foldLeft(List(target)){
case (acc: List[Range], range: Range) =>
acc.flatMap( r => smartDiff(r, range) )
}
val potential = remainingRanges.flatten.toSet

val spotsOnLine = potential diff beaconsOnLine.map( b => b.x )
spotsOnLine.map( x => Position(x, line) )
}
def tuningFrequency(p: Position): BigInt = BigInt(p.x) * 4_000_000 + p.y

println(spots.mkString(", "))
assert(spots.size == 1)
tuningFrequency(spots.head)

Final Code

case class Position(x: Int, y: Int)

def parse(input: String): List[(Position, Position)] =
input.split("\n").toList.map{
case s"Sensor at x=$sx, y=$sy: closest beacon is at x=$bx, y=$by" =>
(Position(sx.toInt, sy.toInt), Position(bx.toInt, by.toInt))
}

def distance(p1: Position, p2: Position): Int =
Math.abs(p1.x - p2.x) + Math.abs(p1.y - p2.y)

def distanceToLine(p: Position, y: Int): Int =
Math.abs(p.y - y)

def lineCoverage(sensor: Position, radius: Int, lineY: Int): Range =
val radiusInLine = radius - distanceToLine(sensor, lineY)

// if radiusInLine is smaller than 0, the range will be empty
(sensor.x - radiusInLine) to (sensor.x + radiusInLine)

def coverOfLine(sensorsWithDistances: List[(Position, Int)], line: Int) =
sensorsWithDistances.map( (sensor, radius) => lineCoverage(sensor, radius, line) ).filter(_.nonEmpty)

def smartDiff(r1: Range, r2: Range): List[Range] =
val innit = r1.start to Math.min(r2.start - 1, r1.last)
val tail = Math.max(r1.start, r2.last + 1) to r1.last
val res = if innit == tail then
List(innit)
else
List(innit, tail)
res.filter(_.nonEmpty).toList

def remainingSpots(target: Range, cover: List[Range]): Set[Int] =

def rec(partialTarget: List[Range], remainingCover: List[Range]): List[Range] =
if remainingCover.isEmpty then
partialTarget
else
val (curr: Range) :: rest = remainingCover: @unchecked
rec(
partialTarget = partialTarget.flatMap( r => smartDiff(r, curr) ),
remainingCover = rest
)

rec(List(target), cover).flatten.toSet

def part1(input: String): Int =
val parsed: List[(Position, Position)] = parse(input)
val beacons: Set[Position] = parsed.map(_._2).toSet
val sensorsWithDistances: List[(Position, Int)] =
parsed.map( (sensor, beacon) => (sensor, distance(sensor, beacon)) )

val line = 2000000
val cover: List[Range] = coverOfLine(sensorsWithDistances, line)
val beaconsOnLine: Set[Position] = beacons.filter(_.y == line)
val count: Int = cover.map(_.size).sum - beaconsOnLine.size
count

def part2(input: String): Any =

val parsed: List[(Position, Position)] = parse(input)
val beacons: Set[Position] = parsed.map(_._2).toSet
val sensorsWithDistances: List[(Position, Int)] =
parsed.map( (sensor, beacon) => (sensor, distance(sensor, beacon)) )

val target: Range = 0 to 4_000_000
val spots: Seq[Position] = target.flatMap{
line =>
val cover: List[Range] = coverOfLine(sensorsWithDistances, line)
val beaconsOnLine: Set[Position] = beacons.filter(_.y == line)

val remainingRanges: List[Range] = cover.foldLeft(List(target)){
case (acc: List[Range], range: Range) =>
acc.flatMap( r => smartDiff(r, range) )
}
val potential = remainingRanges.flatten.toSet

val spotsOnLine = potential diff beaconsOnLine.map( b => b.x )
spotsOnLine.map( x => Position(x, line) )
}
def tuningFrequency(p: Position): BigInt = BigInt(p.x) * 4_000_000 + p.y

println(spots.mkString(", "))
assert(spots.size == 1)
tuningFrequency(spots.head)

Solutions from the community

Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

- + \ No newline at end of file diff --git a/2022/puzzles/day16/index.html b/2022/puzzles/day16/index.html index 250967ca5..51cc86eab 100644 --- a/2022/puzzles/day16/index.html +++ b/2022/puzzles/day16/index.html @@ -5,14 +5,14 @@ Day 16: Proboscidea Volcanium | Scala Center Advent of Code - +
Skip to main content

Day 16: Proboscidea Volcanium

code by Tyler Coles (javadocmd.com), Quentin Bernet, @sjrd, and @bishabosha

Puzzle description

https://adventofcode.com/2022/day/16

Final Code

type Id = String
case class Room(id: Id, flow: Int, tunnels: List[Id])

type Input = List[Room]
// $_ to avoid tunnel/tunnels distinction and so on
def parse(xs: String): Input = xs.split("\n").map{ case s"Valve $id has flow rate=$flow; tunnel$_ lead$_ to valve$_ $tunnelsStr" =>
val tunnels = tunnelsStr.split(", ").toList
Room(id, flow.toInt, tunnels)
}.toList

case class RoomsInfo(
/** map of rooms by id */
rooms: Map[Id, Room],
/** map from starting room to a map containing the best distance to all other rooms */
routes: Map[Id, Map[Id, Int]],
/** rooms containing non-zero-flow valves */
valves: Set[Id]
)

// precalculate useful things like pathfinding
def constructInfo(input: Input): RoomsInfo =
val rooms: Map[Id, Room] = Map.from(for r <- input yield r.id -> r)
val valves: Set[Id] = Set.from(for r <- input if r.flow > 0 yield r.id)
val tunnels: Map[Id, List[Id]] = rooms.mapValues(_.tunnels).toMap
val routes: Map[Id, Map[Id, Int]] = (valves + "AA").iterator.map{ id => id -> computeRoutes(id, tunnels) }.toMap
RoomsInfo(rooms, routes, valves)

// a modified A-star to calculate the best distance to all rooms rather then the best path to a single room
def computeRoutes(start: Id, neighbors: Id => List[Id]): Map[Id, Int] =

case class State(frontier: List[(Id, Int)], scores: Map[Id, Int]):

private def getScore(id: Id): Int = scores.getOrElse(id, Int.MaxValue)
private def setScore(id: Id, s: Int) = State((id, s + 1) :: frontier, scores + (id -> s))

def dequeued: (Id, State) =
val sorted = frontier.sortBy(_._2)
(sorted.head._1, copy(frontier = sorted.tail))

def considerEdge(from: Id, to: Id): State =
val toScore = getScore(from) + 1
if toScore >= getScore(to) then this
else setScore(to, toScore)
end State

object State:
def initial(start: Id) = State(List((start, 0)), Map(start -> 0))

def recurse(state: State): State =
if state.frontier.isEmpty then
state
else
val (curr, currState) = state.dequeued
val newState = neighbors(curr)
.foldLeft(currState) { (s, n) =>
s.considerEdge(curr, n)
}
recurse(newState)

recurse(State.initial(start)).scores

end computeRoutes


// find the best path (the order of valves to open) and the total pressure released by taking it
def bestPath(map: RoomsInfo, start: Id, valves: Set[Id], timeAllowed: Int): Int =
// each step involves moving to a room with a useful valve and opening it
// we don't need to track each (empty) room in between
// we limit our options by only considering the still-closed valves
// and `valves` has already culled any room with a flow value of 0 -- no point in considering these rooms!

val valvesLookup = IArray.from(valves)
val valveCount = valvesLookup.size
val _activeValveIndices = Array.fill[Boolean](valveCount + 1)(true) // add an extra valve for the initial state
def valveIndexLeft(i: Int) = _activeValveIndices(i)
def withoutValve(i: Int)(f: => Int) =
_activeValveIndices(i) = false
val result = f
_activeValveIndices(i) = true
result
val roomsByIndices = IArray.tabulate(valveCount)(i => map.rooms(valvesLookup(i)))

def recurse(hiddenValve: Int, current: Id, timeLeft: Int, totalValue: Int): Int = withoutValve(hiddenValve):
// recursively consider all plausible options
// we are finished when we no longer have time to reach another valve or all valves are open
val routesOfCurrent = map.routes(current)
var bestValue = totalValue
for index <- 0 to valveCount do
if valveIndexLeft(index) then
val id = valvesLookup(index)
val distance = routesOfCurrent(id)
// how much time is left after we traverse there and open the valve?
val t = timeLeft - distance - 1
// if `t` is zero or less this option can be skipped
if t > 0 then
// the value of choosing a particular valve (over the life of our simulation)
// is its flow rate multiplied by the time remaining after opening it
val value = roomsByIndices(index).flow * t
val recValue = recurse(hiddenValve = index, id, t, totalValue + value)
if recValue > bestValue then
bestValue = recValue
end if
end if
end for
bestValue
end recurse
recurse(valveCount, start, timeAllowed, 0)

def part1(input: String) =
val time = 30
val map = constructInfo(parse(input))
bestPath(map, "AA", map.valves, time)
end part1

def part2(input: String) =
val time = 26
val map = constructInfo(parse(input))

// in the optimal solution, the elephant and I will have divided responsibility for switching the valves
// 15 (useful valves) choose 7 (half) yields only 6435 possible divisions which is a reasonable search space!
val valvesA = map.valves.toList
.combinations(map.valves.size / 2)
.map(_.toSet)

// NOTE: I assumed an even ditribution of valves would be optimal, and that turned out to be true.
// However I suppose it's possible an uneven distribution could have been optimal for some graphs.
// To be safe, you could re-run this using all reasonable values of `n` for `combinations` (1 to 7) and
// taking the best of those.

// we can now calculate the efforts separately and sum their values to find the best
val allPaths =
for va <- valvesA yield
val vb = map.valves -- va
val scoreA = bestPath(map, "AA", va, time)
val scoreB = bestPath(map, "AA", vb, time)
scoreA + scoreB

allPaths.max
end part2

Run it in the browser

Part 1

Warning: This is pretty slow and may cause the UI to freeze (close tab if problematic)

Part 2

Warning: This is pretty slow and may cause the UI to freeze (close tab if problematic)

Solutions from the community

Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

- + \ No newline at end of file diff --git a/2022/puzzles/day17/index.html b/2022/puzzles/day17/index.html index dbd5f8200..eae07045c 100644 --- a/2022/puzzles/day17/index.html +++ b/2022/puzzles/day17/index.html @@ -5,14 +5,14 @@ Day 17: Pyroclastic Flow | Scala Center Advent of Code - +
Skip to main content
- + \ No newline at end of file diff --git a/2022/puzzles/day18/index.html b/2022/puzzles/day18/index.html index ec119bf67..d06aafeaf 100644 --- a/2022/puzzles/day18/index.html +++ b/2022/puzzles/day18/index.html @@ -5,13 +5,13 @@ Day 18: Boiling Boulders | Scala Center Advent of Code - +
Skip to main content

Day 18: Boiling Boulders

by LaurenceWarne

Puzzle description

https://adventofcode.com/2022/day/18

Solution

Part 1

To solve the first part, we can first count the total number of cubes and multiply this by six (as a cube has six sides), and then subtract the number of sides which are connected.

As this requires checking if two cubes are adjacent, let's first define a function which we can use to determine cubes adjacent to a given cube:

def adjacent(x: Int, y: Int, z: Int): Set[(Int, Int, Int)] = {
Set(
(x + 1, y, z),
(x - 1, y, z),
(x, y + 1, z),
(x, y - 1, z),
(x, y, z + 1),
(x, y, z - 1)
)
}
info

Note that since cubes are given to be 1⨉1⨉1, they can be represented as a single integral (x, y, z) coordinate which makes up the input for the adjacent function. Then two cubes are adjacent (one of each of their sides touch) if and only if exactly one of their (x, y, z) components differ by one, and the rest by zero.

Now given our cubes, we can implement our strategy with a fold:

def sides(cubes: Set[(Int, Int, Int)]): Int = {
cubes.foldLeft(0) { case (total, (x, y, z)) =>
val adj = adjacent(x, y, z)
val numAdjacent = adj.filter(cubes).size
total + 6 - numAdjacent
}
}

We use a Set for fast fast membership lookups which we need to determine which adjacent spaces for a given cube contain other cubes.

Part 2

The second part is a bit more tricky. Lets introduce some nomenclature: we'll say a 1⨉1⨉1 empty space is on the interior if it lies in an air pocket, else we'll say the space is on the exterior.

A useful observation is that if we consider empty spaces which have a taxicab distance of at most two from any cube, and join these spaces into connected components, then the connected components we are left with form distinct air pockets in addition to one component containing empty spaces on the exterior.

This component can always be identified since the space with the largest x component will always lie in it. So we can determine empty spaces in the interior adjacent to cubes like so:

def interior(cubes: Set[(Int, Int, Int)]): Set[(Int, Int, Int)] = {
val allAdj = cubes.flatMap((x, y, z) => adjacent(x, y, z).filterNot(cubes))
val sts = allAdj.map { case adj @ (x, y, z) =>
adjacent(x, y, z).filterNot(cubes) + adj
}
def cc(sts: List[Set[(Int, Int, Int)]]): List[Set[(Int, Int, Int)]] = {
sts match {
case Nil => Nil
case set :: rst =>
val (matching, other) = rst.partition(s => s.intersect(set).nonEmpty)
val joined = matching.foldLeft(set)(_ ++ _)
if (matching.nonEmpty) cc(joined :: other) else joined :: cc(other)
}
}
val conn = cc(sts.toList)
val exterior = conn.maxBy(_.maxBy(_(0)))
conn.filterNot(_ == exterior).foldLeft(Set())(_ ++ _)
}

Where the nested function cc is used to generate a list of connected components. We can now slightly modify our sides function to complete part two:

def sidesNoPockets(cubes: Set[(Int, Int, Int)]): Int = {
val int = interior(cubes)
val allAdj = cubes.flatMap(adjacent)
allAdj.foldLeft(sides(cubes)) { case (total, (x, y, z)) =>
val adj = adjacent(x, y, z)
if (int((x, y, z))) total - adj.filter(cubes).size else total
}
}

Let's put this all together:

def part1(input: String): Int = sides(cubes(input))
def part2(input: String): Int = sidesNoPockets(cubes(input))

def cubes(input: String): Set[(Int, Int, Int)] =
val cubesIt = input.linesIterator.collect {
case s"$x,$y,$z" => (x.toInt, y.toInt, z.toInt)
}
cubesIt.toSet

Which gives use our desired results.

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2022/puzzles/day19/index.html b/2022/puzzles/day19/index.html index 087f64d3d..25a3776a3 100644 --- a/2022/puzzles/day19/index.html +++ b/2022/puzzles/day19/index.html @@ -5,14 +5,14 @@ Day 19: Not Enough Minerals | Scala Center Advent of Code - +
Skip to main content
- + \ No newline at end of file diff --git a/2022/puzzles/day20/index.html b/2022/puzzles/day20/index.html index 6971ea4e1..21a439180 100644 --- a/2022/puzzles/day20/index.html +++ b/2022/puzzles/day20/index.html @@ -5,14 +5,14 @@ Day 20: Grove Positioning System | Scala Center Advent of Code - +
Skip to main content
- + \ No newline at end of file diff --git a/2022/puzzles/day21/index.html b/2022/puzzles/day21/index.html index d5a66b779..51637e09e 100644 --- a/2022/puzzles/day21/index.html +++ b/2022/puzzles/day21/index.html @@ -5,14 +5,14 @@ Day 21: Monkey Math | Scala Center Advent of Code - +
Skip to main content

Day 21: Monkey Math

Puzzle description

https://adventofcode.com/2022/day/21

Final Code

import annotation.tailrec
import Operation.*

def part1(input: String): Long =
resolveRoot(input)

def part2(input: String): Long =
whichValue(input)

enum Operator(val eval: BinOp, val invRight: BinOp, val invLeft: BinOp):
case `+` extends Operator(_ + _, _ - _, _ - _)
case `-` extends Operator(_ - _, _ + _, (x, y) => y - x)
case `*` extends Operator(_ * _, _ / _, _ / _)
case `/` extends Operator(_ / _, _ * _, (x, y) => y / x)

enum Operation:
case Binary(op: Operator, depA: String, depB: String)
case Constant(value: Long)

type BinOp = (Long, Long) => Long
type Resolved = Map[String, Long]
type Source = Map[String, Operation]
type Substitutions = List[(String, PartialFunction[Operation, Operation])]

def readAll(input: String): Map[String, Operation] =
Map.from(
for case s"$name: $action" <- input.linesIterator yield
name -> action.match
case s"$x $binop $y" =>
Binary(Operator.valueOf(binop), x, y)
case n =>
Constant(n.toLong)
)

@tailrec
def reachable(names: List[String], source: Source, resolved: Resolved): Resolved = names match
case name :: rest =>
source.get(name) match
case None => resolved // return as name is not reachable
case Some(operation) => operation match
case Binary(op, x, y) =>
(resolved.get(x), resolved.get(y)) match
case (Some(a), Some(b)) =>
reachable(rest, source, resolved + (name -> op.eval(a, b)))
case _ =>
reachable(x :: y :: name :: rest, source, resolved)
case Constant(value) =>
reachable(rest, source, resolved + (name -> value))
case Nil =>
resolved
end reachable

def resolveRoot(input: String): Long =
val values = reachable("root" :: Nil, readAll(input), Map.empty)
values("root")

def whichValue(input: String): Long =
val source = readAll(input) - "humn"

@tailrec
def binarySearch(name: String, goal: Option[Long], resolved: Resolved): Long =

def resolve(name: String) =
val values = reachable(name :: Nil, source, resolved)
values.get(name).map(_ -> values)

def nextGoal(inv: BinOp, value: Long): Long = goal match
case Some(prev) => inv(prev, value)
case None => value

(source.get(name): @unchecked) match
case Some(Operation.Binary(op, x, y)) =>
((resolve(x), resolve(y)): @unchecked) match
case (Some(xValue -> resolvedX), _) => // x is known, y has a hole
binarySearch(y, Some(nextGoal(op.invLeft, xValue)), resolvedX)
case (_, Some(yValue -> resolvedY)) => // y is known, x has a hole
binarySearch(x, Some(nextGoal(op.invRight, yValue)), resolvedY)
case None =>
goal.get // hole found
end binarySearch

binarySearch(goal = None, name = "root", resolved = Map.empty)
end whichValue

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

- + \ No newline at end of file diff --git a/2022/puzzles/day22/index.html b/2022/puzzles/day22/index.html index 168167ef4..a8bba960d 100644 --- a/2022/puzzles/day22/index.html +++ b/2022/puzzles/day22/index.html @@ -5,14 +5,14 @@ Day 22: Monkey Map | Scala Center Advent of Code - +
Skip to main content
- + \ No newline at end of file diff --git a/2022/puzzles/day23/index.html b/2022/puzzles/day23/index.html index 349e51bcc..04c88d0cc 100644 --- a/2022/puzzles/day23/index.html +++ b/2022/puzzles/day23/index.html @@ -5,14 +5,14 @@ Day 23: Unstable Diffusion | Scala Center Advent of Code - +
Skip to main content
- + \ No newline at end of file diff --git a/2022/puzzles/day24/index.html b/2022/puzzles/day24/index.html index 9da743888..83a840212 100644 --- a/2022/puzzles/day24/index.html +++ b/2022/puzzles/day24/index.html @@ -5,13 +5,13 @@ Day 24: Blizzard Basin | Scala Center Advent of Code - +
Skip to main content

Day 24: Blizzard Basin

Puzzle description

https://adventofcode.com/2022/day/24

Solution

Today's problem is similar to Day 12, where we need to find our way through a maze. It's made more challenging by impassable blizzards moving through the maze. We can use a similar approach to that of Day 12 still, but we'll improve a little bit further by using A* search instead of a standard breadth first search.

We'll need some kind of point and a few functions that are useful on the 2d grid. A simple tuple (Int, Int) will suffice, and we'll add the functions as extension methods. We'll use Manhattan distance as the A* heuristic function, and we'll need the neighbours in cardinal directions.

type Coord = (Int, Int)
extension (coord: Coord)
def x = coord._1
def y = coord._2
def up = (coord.x, coord.y - 1)
def down = (coord.x, coord.y + 1)
def left = (coord.x - 1, coord.y)
def right = (coord.x + 1, coord.y)
def cardinals = Seq(coord.up, coord.down, coord.left, coord.right)
def manhattan(rhs: Coord) = (coord.x - rhs.x).abs + (coord.y - rhs.y).abs
def +(rhs: Coord) = (coord.x + rhs.x, coord.y + rhs.y)

Before we get to the search, let's deal with the input.

case class Blizzard(at: Coord, direction: Coord)

def parseMaze(in: Seq[String]) =
val start = (in.head.indexOf('.'), 0) // start in the empty spot in the top row
val end = (in.last.indexOf('.'), in.size - 1) // end in the empty spot in the bottom row
val xDomain = 1 to in.head.size - 2 // where blizzards are allowed to go
val yDomain = 1 to in.size - 2
val initialBlizzards =
for
y <- in.indices
x <- in(y).indices
if in(y)(x) != '.' // these aren't blizzards!
if in(y)(x) != '#'
yield in(y)(x) match
case '>' => Blizzard(at = (x, y), direction = (1, 0))
case '<' => Blizzard(at = (x, y), direction = (-1, 0))
case '^' => Blizzard(at = (x, y), direction = (0, -1))
case 'v' => Blizzard(at = (x, y), direction = (0, 1))

??? // ...to be implemented

Ok, let's deal with the blizzards. The blizzards move toroidally, which is to say they loop around back to the start once they fall off an edge. This means that, eventually, the positions and directions of all blizzards must loop at some point. Naively, after xDomain.size * yDomain.size minutes, every blizzard must have returned to it's original starting location. Let's model that movement and calculate the locations of all the blizzards up until that time. With it, we'll have a way to tell us where the blizzards are at a given time t, for any t.

def move(blizzard: Blizzard, xDomain: Range, yDomain: Range) =
blizzard.copy(at = cycle(blizzard.at + blizzard.direction, xDomain, yDomain))

def cycle(coord: Coord, xDomain: Range, yDomain: Range): Coord = (cycle(coord.x, xDomain), cycle(coord.y, yDomain))

def cycle(n: Int, bounds: Range): Int =
if n > bounds.max then bounds.min // we've fallen off the end, go to start
else if n < bounds.min then bounds.max // we've fallen off the start, go to the end
else n // we're chillin' in bounds still

We can replace the ??? in parseMaze now. And we'll need a return type for the function. We can cram everything into a Maze case class. For the blizzards, we actually only need to care about where they are after this point, as they'll prevent us from moving to those locations. We'll throw away the directions and just keep the set of Coords the blizzards are at.

case class Maze(xDomain: Range, yDomain: Range, blizzards: Seq[Set[Coord]], start: Coord, end: Coord)

def parseMaze(in: Seq[String]): Maze =
/* ...omitted for brevity... */
def tick(blizzards: Seq[Blizzard]) = blizzards.map(move(_, xDomain, yDomain))
val allBlizzardLocations = Iterator.iterate(initialBlizzards)(tick)
.take(xDomain.size * yDomain.size)
.map(_.map(_.at).toSet)
.toIndexedSeq

Maze(xDomain, yDomain, allBlizzardLocations, start, end)

But! We can do a little better for the blizzards. The blizzards actually cycle for any common multiple of xDomain.size and yDomain.size. Using the least common multiple would be sensible to do the least amount of computation.

def gcd(a: Int, b: Int): Int = if b == 0 then a else gcd(b, a % b)
def lcm(a: Int, b: Int): Int = a * b / gcd(a, b)
def tick(blizzards: Seq[Blizzard]) = blizzards.map(move(_, xDomain, yDomain))
val allBlizzardLocations = Iterator.iterate(initialBlizzards)(tick)
.take(lcm(xDomain.size, yDomain.size))
.map(_.map(_.at).toSet)
.toIndexedSeq

Great! Let's solve the maze.

import scala.collection.mutable
case class Step(at: Coord, time: Int)

def solve(maze: Maze): Step =
// order A* options by how far we've taken + an estimated distance to the end
given Ordering[Step] = Ordering[Int].on((step: Step) => step.at.manhattan(maze.end) + step.time).reverse
val queue = mutable.PriorityQueue[Step]()
val visited = mutable.Set.empty[Step]

def inBounds(coord: Coord) = coord match
case c if c == maze.start || c == maze.end => true
case c => maze.xDomain.contains(c.x) && maze.yDomain.contains(c.y)

queue += Step(at = maze.start, time = 0)
while queue.head.at != maze.end do
val step = queue.dequeue
val time = step.time + 1
// where are the blizzards for our next step? we can't go there
val blizzards = maze.blizzards(time % maze.blizzards.size)
// we can move in any cardinal direction, or chose to stay put; but it needs to be in the maze
val options = (step.at.cardinals :+ step.at).filter(inBounds).map(Step(_, time))
// queue up the options if they are possible; and if we have not already queued them
queue ++= options
.filterNot(o => blizzards(o.at)) // the option must not be in a blizzard
.filterNot(visited) // avoid duplicate work
.tapEach(visited.add) // keep track of what we've enqueued

queue.dequeue

That's pretty much it! Part 1 is then:

def part1(in: Seq[String]) = solve(parseMaze(in)).time

Part 2 requires solving the maze 3 times. Make it to the end (so, solve part 1 again), go back to the start, then go back to the end. We can use the same solve function, but we need to generalize a bit so we can start the solver at an arbitrary time. This will allow us to keep the state of the blizzards for subsequent runs. We actually only need to change one line!

def solve(maze: Maze, startingTime: Int = 0): Step =
/* the only line we need to change is... */
queue += Step(at = maze.start, time = startingTime)

Then part 2 requires calling solve 3 times. We need to be a little careful with the start/end locations and starting times.

def part2(in: Seq[String]) =
val maze = parseMaze(in)
val first = solve(maze)
val second = solve(maze.copy(start = maze.end, end = maze.start), first.time)
solve(maze, second.time).time

That's Day 24. Huzzah!

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2022/puzzles/day25/index.html b/2022/puzzles/day25/index.html index 6087c4901..be4aa40c6 100644 --- a/2022/puzzles/day25/index.html +++ b/2022/puzzles/day25/index.html @@ -5,14 +5,14 @@ Day 25: Full of Hot Air | Scala Center Advent of Code - +
Skip to main content

Day 25: Full of Hot Air

Puzzle description

https://adventofcode.com/2022/day/25

Final Code

def part1(input: String): String =
totalSnafu(input)

val digitToInt = Map(
'0' -> 0,
'1' -> 1,
'2' -> 2,
'-' -> -1,
'=' -> -2,
)
val intToDigit = digitToInt.map(_.swap)

def showSnafu(value: Long): String =
val reverseDigits = Iterator.unfold(value)(v =>
Option.when(v != 0) {
val mod = math.floorMod(v, 5).toInt
val digit = if mod > 2 then mod - 5 else mod
intToDigit(digit) -> (v - digit) / 5
}
)
if reverseDigits.isEmpty then "0"
else reverseDigits.mkString.reverse

def readSnafu(line: String): Long =
line.foldLeft(0L)((acc, digit) =>
acc * 5 + digitToInt(digit)
)

def totalSnafu(input: String): String =
showSnafu(value = input.linesIterator.map(readSnafu).sum)

Run it in the browser

Part 1 (Only 1 part today)

Solutions from the community

Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

- + \ No newline at end of file diff --git a/2023/index.html b/2023/index.html index 8b12337d6..afe365e16 100644 --- a/2023/index.html +++ b/2023/index.html @@ -5,13 +5,13 @@ Scala Center Advent of Code | Scala Center Advent of Code - +
Skip to main content
Credit to https://github.com/OlegIlyenko/scala-icon

Learn Scala 3

A simpler, safer and more concise version of Scala, the famous object-oriented and functional programming language.

Solve Advent of Code puzzles

Challenge your programming skills by solving Advent of Code puzzles.

Share with the community

Get or give support to the community. Share your solutions with the community.

- + \ No newline at end of file diff --git a/2023/puzzles/day01/index.html b/2023/puzzles/day01/index.html index 2fe7fd932..b17fbd780 100644 --- a/2023/puzzles/day01/index.html +++ b/2023/puzzles/day01/index.html @@ -5,7 +5,7 @@ Day 1: Trebuchet?! | Scala Center Advent of Code - + @@ -22,7 +22,7 @@ Instead, we manually iterate over all the indices to see if a match starts there. This is equivalent to looking for prefix matches in all the suffixes of line. Conveniently, line.tails iterates over all such suffixes, and Regex.findPrefixOf will look only for prefixes.

Our fixed computation for matches is now:

val matchesIter =
for
lineTail <- line.tails
oneMatch <- digitReprRegex.findPrefixOf(lineTail)
yield
oneMatch
val matches = matchesIter.toList

Final Code

def part1(input: String): String =
// Convert one line into the appropriate coordinates
def lineToCoordinates(line: String): Int =
val firstDigit = line.find(_.isDigit).get
val lastDigit = line.findLast(_.isDigit).get
s"$firstDigit$lastDigit".toInt

// Convert each line to its coordinates and sum all the coordinates
val result = input
.linesIterator
.map(lineToCoordinates(_))
.sum
result.toString()
end part1

/** The textual representation of digits. */
val stringDigitReprs = Map(
"one" -> 1,
"two" -> 2,
"three" -> 3,
"four" -> 4,
"five" -> 5,
"six" -> 6,
"seven" -> 7,
"eight" -> 8,
"nine" -> 9,
)

/** All the string representation of digits, including the digits themselves. */
val digitReprs = stringDigitReprs ++ (1 to 9).map(i => i.toString() -> i)

def part2(input: String): String =
// A regex that matches any of the keys of `digitReprs`
val digitReprRegex = digitReprs.keysIterator.mkString("|").r

def lineToCoordinates(line: String): Int =
// Find all the digit representations in the line
val matchesIter =
for
lineTail <- line.tails
oneMatch <- digitReprRegex.findPrefixOf(lineTail)
yield
oneMatch
val matches = matchesIter.toList

// Convert the string representations into actual digits and form the result
val firstDigit = digitReprs(matches.head)
val lastDigit = digitReprs(matches.last)
s"$firstDigit$lastDigit".toInt
end lineToCoordinates

// Process lines as in part1
val result = input
.linesIterator
.map(lineToCoordinates(_))
.sum
result.toString()
end part2

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2023/puzzles/day02/index.html b/2023/puzzles/day02/index.html index 0f8669c90..23c4cc4dd 100644 --- a/2023/puzzles/day02/index.html +++ b/2023/puzzles/day02/index.html @@ -5,7 +5,7 @@ Day 2: Cube Conundrum | Scala Center Advent of Code - + @@ -14,7 +14,7 @@ In a single pass over the puzzle input it will:

case class Colors(color: String, count: Int)
case class Game(id: Int, hands: List[List[Colors]])
type Summary = Game => Int

def solution(input: String, summarise: Summary): Int =
input.linesIterator.map(parse andThen summarise).sum

def parse(line: String): Game = ???

part1 and part2 will use this framework, plugging in the appropriate summarise function.

Parsing

Let's fill in the parse function as follows:

def parseColors(pair: String): Colors =
val (s"$value $name") = pair: @unchecked
Colors(color = name, count = value.toInt)

def parse(line: String): Game =
val (s"Game $id: $hands0") = line: @unchecked
val hands1 = hands0.split("; ").toList
val hands2 = hands1.map(_.split(", ").toList.map(parseColors))
Game(id = id.toInt, hands = hands2)

Summary

As described above, to summarise each game, we evaluate it as a possibleGame, where if it is a validGame summarise as the game's id, otherwise 0.

A game is valid if for all hands in the game, all the colors in each hand has a count that is less-than or equal-to the count of same color from the possibleCubes configuration.

val possibleCubes = Map(
"red" -> 12,
"green" -> 13,
"blue" -> 14,
)

def validGame(game: Game): Boolean =
game.hands.forall: hand =>
hand.forall:
case Colors(color, count) =>
count <= possibleCubes.getOrElse(color, 0)

val possibleGame: Summary =
case game if validGame(game) => game.id
case _ => 0

def part1(input: String): Int = solution(input, possibleGame)

Part 2

Summary

In part 2, the summary of a game requires us to find the minimumCubes necessary to make a possible game. What this means is for any given game, across all hands calculating the maximum cubes drawn for each color.

In Scala we can accumulate the maximum counts for each cube in a Map from color to count. Take the initial maximums as all zero:

val initial = Seq("red", "green", "blue").map(_ -> 0).toMap

Then for each game we can compute the maximum cubes drawn in each game as follows

def minimumCubes(game: Game): Int =
var maximums = initial
for
hand <- game.hands
Colors(color, count) <- hand
do
maximums += (color -> (maximums(color) `max` count))
maximums.values.product

Finally we can complete the solution by using minimumCubes to summarise each game:

def part2(input: String): Int = solution(input, minimumCubes)

Final Code

case class Colors(color: String, count: Int)
case class Game(id: Int, hands: List[List[Colors]])
type Summary = Game => Int

def parseColors(pair: String): Colors =
val (s"$value $name") = pair: @unchecked
Colors(color = name, count = value.toInt)

def parse(line: String): Game =
val (s"Game $id: $hands0") = line: @unchecked
val hands1 = hands0.split("; ").toList
val hands2 = hands1.map(_.split(", ").toList.map(parseColors))
Game(id = id.toInt, hands = hands2)

def solution(input: String, summarise: Summary): Int =
input.linesIterator.map(parse andThen summarise).sum

val possibleCubes = Map(
"red" -> 12,
"green" -> 13,
"blue" -> 14,
)

def validGame(game: Game): Boolean =
game.hands.forall: hand =>
hand.forall:
case Colors(color, count) =>
count <= possibleCubes.getOrElse(color, 0)

val possibleGame: Summary =
case game if validGame(game) => game.id
case _ => 0

def part1(input: String): Int = solution(input, possibleGame)

val initial = Seq("red", "green", "blue").map(_ -> 0).toMap

def minimumCubes(game: Game): Int =
var maximums = initial
for
hand <- game.hands
Colors(color, count) <- hand
do
maximums += (color -> (maximums(color) `max` count))
maximums.values.product

def part2(input: String): Int = solution(input, minimumCubes)

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2023/puzzles/day03/index.html b/2023/puzzles/day03/index.html index 35f44185f..38cf63548 100644 --- a/2023/puzzles/day03/index.html +++ b/2023/puzzles/day03/index.html @@ -5,13 +5,13 @@ Day 3: Gear Ratios | Scala Center Advent of Code - +
Skip to main content

Day 3: Gear Ratios

by @bishabosha and @iusildra

Puzzle description

https://adventofcode.com/2023/day/3

Solution summary

The solution models the input as a grid of numbers and symbols.

  1. Define some models to represent the input:
    • case class Coord(x: Int, y: Int) to represent one coordinate on the grid
    • case class Symbol(sym: String, pos: Coord) to represent one symbol and its location
    • case class PartNumber(value: Int, start: Coord, end: Coord) to represent one number and its starting/ending location
  2. Parse the input to create a sparse collection of symbols and numbers
  3. Separate the symbols from the numbers
  4. Then summarise the whole grid as follows:
    • in part1, find all numbers adjacent to a symbol, and sum the total of the resulting number values,
    • in part2,
      1. Find all numbers adjacent to a symbol whose char value is *
      2. Filter out the * symbol with less/more than 2 adjacent numbers
      3. For each * symbol remaining, take the product of its two number values
      4. Sum the resulting products
    • a symbol is adjacent to a number (and vice-versa) if that symbol is inside the number's bounding box on the grid at 1 unit away (see manhattan distance)

Global

We want a convenient way to represent a coordinate to be able to compute whether one element is within the bounding box of another.

case class Coord(x: Int, y: Int):
def within(start: Coord, end: Coord) =
if y < start.y || y > end.y then false
else if x < start.x || x > end.x then false
else true

We also want to easily distinguish a Symbol from a Number, and to know whether a Symbol is adjacent to a Number:

case class PartNumber(value: Int, start: Coord, end: Coord)
case class Symbol(sym: String, pos: Coord):
def neighborOf(number: PartNumber) = pos.within(
Coord(number.start.x - 1, number.start.y - 1),
Coord(number.end.x + 1, number.end.y + 1)
)

Then we need to parse the input to get every Symbol and Number:

import scala.util.matching.Regex.Match

object IsInt:
def unapply(in: Match): Option[Int] = in.matched.toIntOption

def findPartsAndSymbols(source: String) =
val extractor = """(\d+)|[^.\d]""".r
source.split("\n").zipWithIndex.flatMap: (line, i) =>
extractor
.findAllMatchIn(line)
.map:
case m @ IsInt(nb) =>
PartNumber(nb, Coord(m.start, i), Coord(m.end - 1, i))
case s => Symbol(s.matched, Coord(s.start, i))

The object IsInt with the .unapply method is called an extractor. It allows to define patterns to match on. Here it will give me a number if it can parse it from a string.

The findPartsAndSymbols does the parsing and returns a collection of PartNumber and Symbol. What we want to match on is either a number or a symbol (which is anything except the . and a digit). The regex match gives us some information (such as starting / ending position of the matched string) which we use to create the PartNumber and Symbol instances.

The m @ IsInt(nb) is a pattern match that will match on the IsInt extractor and binds the parsed integer to nb and the value being matched to m. A similar way to achieve this is:

.map: m =>
m match
case IsInt(nb) => PartNumber(nb, Coord(m.start, i), Coord(m.end - 1, i))
case s => Symbol(s.matched, Coord(s.start, i))

Part 1

Compute part1 as described above:

  1. Find all numbers and symbols in the grid
  2. Filter out the symbols in a separate collection
  3. For each number element of the grid and if it has a least one symbol neighbor, return its value
  4. Sum the resulting values
def part1(input: String) =
val all = findPartsAndSymbols(input)
val symbols = all.collect { case s: Symbol => s }
all
.collect:
case n: PartNumber if symbols.exists(_.neighborOf(n)) =>
n.value
.sum

Part 2

We might want to represent a Gear to facilitate the computation of the gear ratios:

case class Gear(part: PartNumber, symbol: Symbol)

(Note: a case class is not necessary here, a tuple would do the job)

Compute part2 as described above:

  1. Find all numbers and symbols in the grid
  2. Filter out the symbols in a separate collection
  3. For each number element of the grid and if it has one * neighbor, return a Gear with the number and the * symbol. For any other cases, return None
    • The .flatMap method will filter out the None values when flattening, so we get a collection of Gear only
  4. Group them by symbol and map the values to the number values
    • So we obtain a Map[Symbol, List[Int]] instead of a Map[Symbol, List[Gear]]
  5. Filter out the symbols with less/more than 2 adjacent numbers
  6. For each entry remaining, take the product of its two number values and sum the resulting products
def part2(input: String) =
val all = findPartsAndSymbols(input)
val symbols = all.collect { case s: Symbol => s }
all
.flatMap:
case n: PartNumber =>
symbols
.find(_.neighborOf(n))
.filter(_.sym == "*")
.map(Gear(n, _))
case _ => None
.groupMap(_.symbol)(_.part.value)
.filter(_._2.length == 2)
.foldLeft(0) { _ + _._2.product }

Final code

case class Coord(x: Int, y: Int):
def within(start: Coord, end: Coord) =
if y < start.y || y > end.y then false
else if x < start.x || x > end.x then false
else true
case class PartNumber(value: Int, start: Coord, end: Coord)
case class Symbol(sym: String, pos: Coord):
def neighborOf(number: PartNumber) = pos.within(
Coord(number.start.x - 1, number.start.y - 1),
Coord(number.end.x + 1, number.end.y + 1)
)

object IsInt:
def unapply(in: Match): Option[Int] = in.matched.toIntOption

def findPartsAndSymbols(source: String) =
val extractor = """(\d+)|[^.\d]""".r
source.split("\n").zipWithIndex.flatMap: (line, i) =>
extractor
.findAllMatchIn(line)
.map:
case m @ IsInt(nb) =>
PartNumber(nb, Coord(m.start, i), Coord(m.end - 1, i))
case s => Symbol(s.matched, Coord(s.start, i))

def part1(input: String) =
val all = findPartsAndSymbols(input)
val symbols = all.collect { case s: Symbol => s }
all
.collect:
case n: PartNumber if symbols.exists(_.neighborOf(n)) =>
n.value
.sum

case class Gear(part: PartNumber, symbol: Symbol)

def part2(input: String) =
val all = findPartsAndSymbols(input)
val symbols = all.collect { case s: Symbol => s }
all
.flatMap:
case n: PartNumber =>
symbols
.find(_.neighborOf(n))
.filter(_.sym == "*")
.map(Gear(n, _))
case _ => None
.groupMap(_.symbol)(_.part.value)
.filter(_._2.length == 2)
.foldLeft(0) { _ + _._2.product }

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2023/puzzles/day04/index.html b/2023/puzzles/day04/index.html index e77fb1430..d950b0d71 100644 --- a/2023/puzzles/day04/index.html +++ b/2023/puzzles/day04/index.html @@ -5,7 +5,7 @@ Day 4: Scratchcards | Scala Center Advent of Code - + @@ -33,7 +33,7 @@ card. (It is summed up in numCards in the accumulator.)

Why track by relative index instead of absolute?

Final code

def countWinning(card: String): Int =
val numbers = card
.substring(card.indexOf(":") + 1) // discard "Card X:"
.split(" ")
.filterNot(_.isEmpty())
val (winningNumberStrs, givenNumberStrs) = numbers.span(_ != "|")
val winningNumbers = winningNumberStrs.map(_.toInt).toSet
// drop the initial "|"
val givenNumbers = givenNumberStrs.drop(1).map(_.toInt).toSet
winningNumbers.intersect(givenNumbers).size
end countWinning

def winningCounts(input: String): Iterator[Int] =
input.linesIterator.map(countWinning)
end winningCounts

def part1(input: String): String =
winningCounts(input)
.map(winning => if winning > 0 then Math.pow(2, winning - 1).toInt else 0)
.sum.toString()
end part1

def part2(input: String): String =
winningCounts(input)
// we only track the multiplicities of the next few cards as needed, not all of them;
// and the first element always exists, and corresponds to the current card;
// and the elements are always positive (because there is at least 1 original copy of each card)
.foldLeft((0, Vector(1))){ case ((numCards, multiplicities), winning) =>
val thisMult = multiplicities(0)
val restMult = multiplicities
.drop(1)
// these are the original copies of the next few cards
.padTo(Math.max(1, winning), 1)
.zipWithIndex
// these are the extra copies we just won
.map((mult, idx) => if idx < winning then mult + thisMult else mult)
(numCards + thisMult, restMult)
}
._1.toString()
end part2

Run it in the browser

Part 1

Part 2

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2023/puzzles/day05/index.html b/2023/puzzles/day05/index.html index 4c7c6e740..6c24633e5 100644 --- a/2023/puzzles/day05/index.html +++ b/2023/puzzles/day05/index.html @@ -5,7 +5,7 @@ Day 5: If You Give A Seed A Fertilizer | Scala Center Advent of Code - + @@ -27,7 +27,7 @@ destinationStart.

Often, there is part of the interval that is above the end of the current property range. In this case we must make a new sub-interval that begins after the end of the property range.

If we do find an above sub-interval, then we need to check that against the next Property. Otherwise then we can shortcut the computation and not check any of the following properties.

def findNext(resource: Resource, map: ResourceMap): Seq[Resource] =
val ResourceMap(from, to, properties) = map
val (newResources, explore) =
val initial = (Seq.empty[Resource], Option(resource))
properties.foldLeft(initial) {
case ((acc, Some(explore)), prop) =>
val Resource(start, end, _) = explore
val propStart = prop.sourceStart
val propEnd = prop.sourceEnd
val underRange = Option.when(start < propStart)(
Resource(start, Math.min(propStart - 1, end), to)
)
val overlaps =
start >= propStart && start <= propEnd
|| end >= propStart && end <= propEnd
|| start <= propStart && end >= propEnd
val inRange = Option.when(overlaps) {
val delay = prop.destinationStart - propStart
Resource(
Math.max(start, propStart) + delay,
Math.min(end, propEnd) + delay,
to
)
}
val aboveRange = Option.when(end > propEnd)(
Resource(Math.max(start, propEnd + 1), end, to)
)
(Seq(underRange, inRange, acc).flatten, aboveRange)
case ((acc, None), _) => (acc, None)
}
Seq(newResources, explore).flatten
end findNext

Parsing

In this section we list the code to parse the input into ResourceMap and Resource.

object ResourceMap:
// parse resource maps from lines
def buildFromLines(lines: Seq[String]): Seq[ResourceMap] =
def isRangeLine(line: String) =
line.forall(ch => ch.isDigit || ch.isSpaceChar)
lines.filter(line =>
!line.isBlank &&
(line.endsWith("map:") || isRangeLine(line))
).foldLeft(Seq.empty[(String, Seq[String])]) {
case (acc, line) if line.endsWith("map:") =>
(line, Seq.empty) +: acc
case (Seq((definition, properties), last*), line) =>
(definition, line +: properties) +: last
}
.flatMap(build)

def build(map: String, ranges: Seq[String]): Option[ResourceMap] =
val mapRow = map.replace("map:", "").trim.split("-to-")
val properties = ranges
.map(line => line.split(" ").flatMap(_.toLongOption))
.collect:
case Array(startFrom, startTo, range) =>
Property(startFrom, startTo, range)
def resourceKindOf(optStr: Option[String]) =
optStr.map(_.capitalize).map(ResourceKind.valueOf)
for
from <- resourceKindOf(mapRow.headOption)
to <- resourceKindOf(mapRow.lastOption)
yield
ResourceMap(from, to, properties.sortBy(_.sourceStart))
end ResourceMap

object Seeds:
private def parseSeedsRaw(line: String): Seq[Long] =
if !line.startsWith("seeds:") then Seq.empty[Long]
else
line.replace("seeds:", "")
.trim
.split(" ")
.flatMap(_.toLongOption)

// parse seeds without range
def parseWithoutRange(line: String): Seq[Resource] =
parseSeedsRaw(line).map: start =>
Resource(start, start, ResourceKind.Seed)

// parse seeds with range
def parse(line: String): Seq[Resource] =
parseSeedsRaw(line)
.grouped(2)
.map { case Seq(start, length) =>
Resource(start, start + length - 1, ResourceKind.Seed)
}
.toSeq
end Seeds

Final Code

final case class Resource(
start: Long, end: Long, kind: ResourceKind)

enum ResourceKind:
case Seed, Soil, Fertilizer, Water,
Light, Temperature, Humidity, Location

final case class ResourceMap(
from: ResourceKind,
to: ResourceKind,
properties: Seq[Property]
)

final case class Property(
destinationStart: Long,
sourceStart: Long,
rangeLength: Long
):

lazy val sourceEnd: Long = sourceStart + rangeLength - 1
end Property

def findNext(resource: Resource, map: ResourceMap): Seq[Resource] =
val ResourceMap(from, to, properties) = map
val (newResources, explore) =
val initial = (Seq.empty[Resource], Option(resource))
properties.foldLeft(initial) {
case ((acc, Some(explore)), prop) =>
val Resource(start, end, _) = explore
val propStart = prop.sourceStart
val propEnd = prop.sourceEnd
val underRange = Option.when(start < propStart)(
Resource(start, Math.min(propStart - 1, end), to)
)
val overlaps =
start >= propStart && start <= propEnd
|| end >= propStart && end <= propEnd
|| start <= propStart && end >= propEnd
val inRange = Option.when(overlaps) {
val delay = prop.destinationStart - propStart
Resource(
Math.max(start, propStart) + delay,
Math.min(end, propEnd) + delay,
to
)
}
val aboveRange = Option.when(end > propEnd)(
Resource(Math.max(start, propEnd + 1), end, to)
)
(Seq(underRange, inRange, acc).flatten, aboveRange)
case ((acc, None), _) => (acc, None)
}
Seq(newResources, explore).flatten
end findNext

object ResourceMap:
// parse resource maps from lines
def buildFromLines(lines: Seq[String]): Seq[ResourceMap] =
def isRangeLine(line: String) =
line.forall(ch => ch.isDigit || ch.isSpaceChar)
lines.filter(line =>
!line.isBlank &&
(line.endsWith("map:") || isRangeLine(line))
).foldLeft(Seq.empty[(String, Seq[String])]) {
case (acc, line) if line.endsWith("map:") =>
(line, Seq.empty) +: acc
case (Seq((definition, properties), last*), line) =>
(definition, line +: properties) +: last
}
.flatMap(build)

def build(map: String, ranges: Seq[String]): Option[ResourceMap] =
val mapRow = map.replace("map:", "").trim.split("-to-")
val properties = ranges
.map(line => line.split(" ").flatMap(_.toLongOption))
.collect:
case Array(startFrom, startTo, range) =>
Property(startFrom, startTo, range)
def resourceKindOf(optStr: Option[String]) =
optStr.map(_.capitalize).map(ResourceKind.valueOf)
for
from <- resourceKindOf(mapRow.headOption)
to <- resourceKindOf(mapRow.lastOption)
yield
ResourceMap(from, to, properties.sortBy(_.sourceStart))
end ResourceMap

object Seeds:
private def parseSeedsRaw(line: String): Seq[Long] =
if !line.startsWith("seeds:") then Seq.empty[Long]
else
line.replace("seeds:", "")
.trim
.split(" ")
.flatMap(_.toLongOption)

// parse seeds without range
def parseWithoutRange(line: String): Seq[Resource] =
parseSeedsRaw(line).map: start =>
Resource(start, start, ResourceKind.Seed)

// parse seeds with range
def parse(line: String): Seq[Resource] =
parseSeedsRaw(line)
.grouped(2)
.map { case Seq(start, length) =>
Resource(start, start + length - 1, ResourceKind.Seed)
}
.toSeq
end Seeds

def calculate(seeds: Seq[Resource], maps: Seq[ResourceMap]): Long =
def inner(resource: Resource): Seq[Resource] =
if resource.kind == ResourceKind.Location then
Seq(resource)
else
val map = maps.find(_.from == resource.kind).get
findNext(resource, map).flatMap(inner)
seeds.flatMap(inner).minBy(_.start).start
end calculate

type ParseSeeds = String => Seq[Resource]

def solution(input: String, parse: ParseSeeds): Long =
val lines = input.linesIterator.toSeq
val seeds = lines.headOption.map(parse).getOrElse(Seq.empty)
val maps = ResourceMap.buildFromLines(lines)
calculate(seeds, maps)

def part1(input: String): Long =
solution(input, Seeds.parseWithoutRange)

def part2(input: String): Long =
solution(input, Seeds.parse)

Solutions from the community

Share your solution to the Scala community by editing this page. (You can even write the whole article!)

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2023/puzzles/day06/index.html b/2023/puzzles/day06/index.html index 67831c946..2b1bde886 100644 --- a/2023/puzzles/day06/index.html +++ b/2023/puzzles/day06/index.html @@ -5,7 +5,7 @@ Day 6: Wait For It | Scala Center Advent of Code - + @@ -33,7 +33,7 @@ We can find the roots as follows:

val disc = math.sqrt(t * t - 4 * d)
val root1 = t / 2 - disc / 2
val root2 = t / 2 + disc / 2

Counting the integers between the roots

The idea is to take the ceiling of the smaller root, the floor of the larger root, then count the integers in this closed interval:

root2.floor - root1.ceil + 1

Edge cases

In one of the given test cases with t = 30 and d = 200 both roots happen to be integers themselves: x1 = 10 and x2 = 20.

quad

In this case, the valid solutions are the integers 11, 12, 13, 14, 15, 16, 17, 18 and 19, excluding the roots themselves. So we have to check if either root is an integer itself, and if so, exclude it. Because the roots give us equality x * (t-x) = d. For the lower endpoint of the interval, we'd have to increase it by 1, and for the upper endpoint we'd have to decrease it by 1.

// are the roots integers themselves?
val int1 = root1.ceil.toLong
val endPt1 = if int1 == root1 then int1 + 1L else int1
val int2 = root2.floor.toLong
val endPt2 = if int2 == root2 then int2 - 1L else int2

Parsing the input

Part 2 deals with large numbers, so we'll have to use Long.

For part 1, we can parse both lines (times and distances) to sequences of Long, then zip them.

// input looks like: Time:        61     67     75     71
// we want: 61, 67, 75, 71
def parse1(line: String) = line match
case s"Time: $x" => x.split(" ").filter(_.nonEmpty).map(_.toLong)
case s"Distance: $x" => x.split(" ").filter(_.nonEmpty).map(_.toLong)

For part 2, we can filter out the space characters to obtain one Long value from each line.

// input looks like: Time:        61     67     75     71
// we want: 61677571
def parse2(line: String) = line match
case s"Time: $x" => x.filterNot(_.isSpaceChar).toLong
case s"Distance: $x" => x.filterNot(_.isSpaceChar).toLong

The input is given in two lines, one for times and one for distances. We can split them with .split("\n").

Final code

Remember that for part 1, we need to multiply the individual results!

def parse1(line: String) = line match
case s"Time: $x" => x.split(" ").filter(_.nonEmpty).map(_.toLong)
case s"Distance: $x" => x.split(" ").filter(_.nonEmpty).map(_.toLong)

def parse2(line: String) = line match
case s"Time: $x" => x.filterNot(_.isSpaceChar).toLong
case s"Distance: $x" => x.filterNot(_.isSpaceChar).toLong

def solve(time: Long, distance: Long): Long =
val (t, d) = (time.toDouble, distance.toDouble)
val disc = math.sqrt(t * t - 4 * d)
val (root1, root2) = (t / 2 - disc / 2, t / 2 + disc / 2)

val int1 = root1.ceil.toLong
val endPt1 = if int1 == root1 then int1 + 1L else int1

val int2 = root2.floor.toLong
val endPt2 = if int2 == root2 then int2 - 1L else int2

endPt2 - endPt1 + 1L

def part1(input: String): Long =
val lines = input.split("\n")
val (times, distances) = (parse1(lines(0)), parse1(lines(1)))
val solutions = times.zip(distances).map((t, d) => solve(t, d))
solutions.product
end part1

def part2(input: String): Long =
val lines = input.split("\n")
val (time, distance) = (parse2(lines(0)), parse2(lines(1)))
solve(time, distance)
end part2

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2023/puzzles/day07/index.html b/2023/puzzles/day07/index.html index c906feb96..399e5e4be 100644 --- a/2023/puzzles/day07/index.html +++ b/2023/puzzles/day07/index.html @@ -5,13 +5,13 @@ Day 7: Camel Cards | Scala Center Advent of Code - +
Skip to main content

Day 7: Camel Cards

by @anatoliykmetyuk

Puzzle description

https://adventofcode.com/2023/day/7

Part 1 Solution

The problem, in its essence, is a simplified version of the classic poker problem where you are required to compare poker hands according to certain rules.

Domain

We'll start by defining the domain of the problem:

type Card = Char
type Hand = String
case class Bet(hand: Hand, bid: Int)
enum HandType:
case HighCard, OnePair, TwoPair, ThreeOfAKind, FullHouse, FourOfAKind, FiveOfAKind

We can then define the constructors to create a Bet and a HandType:

object Bet:
def apply(s: String): Bet = Bet(s.take(5), s.drop(6).toInt)

object HandType:
def apply(hand: Hand): HandType =
val cardCounts: List[Int] =
hand.groupBy(identity).values.toList.map(_.length).sorted.reverse

cardGroups match
case 5 :: _ => HandType.FiveOfAKind
case 4 :: _ => HandType.FourOfAKind
case 3 :: 2 :: Nil => HandType.FullHouse
case 3 :: _ => HandType.ThreeOfAKind
case 2 :: 2 :: _ => HandType.TwoPair
case 2 :: _ => HandType.OnePair
case _ => HandType.HighCard
end apply

A Bet is created from a String e.g. "5678A 364" - that is, the hand and the bid amount.

A HandType is a bit more complicated: it is calculated from Hand - e.g. "5678A" - according to the rules specified in the challenge. Since the essence of hand scoring lies in how many occurrences of a given card there are in the hand, we utilize Scala's declarative collection capabilities to group the cards and calculate their occurrences. We can then use a match expression to look for the occurrences patterns as specified in the challenge, in descending order of value.

Comparison

The objective of the challenge is to sort bets and calculate the final winnings. Let's address the sorting part. Scala collections are good enough at sorting, so we don't need to implement the sorting proper. But for Scala to do its job, it needs to know the ordering function of the elements. We need to define how to compare two bets:

val ranks = "23456789TJQKA"
given cardOrdering: Ordering[Card] = Ordering.by(ranks.indexOf(_))
given handOrdering: Ordering[Hand] = (h1: Hand, h2: Hand) =>
val h1Type = HandType(h1)
val h2Type = HandType(h2)
if h1Type != h2Type then h1Type.ordinal - h2Type.ordinal
else h1.zip(h2).find(_ != _).map( (c1, c2) => cardOrdering.compare(c1, c2) ).getOrElse(0)
given betOrdering: Ordering[Bet] = Ordering.by(_.hand)

We define three orderings: one for cards, one for hands, and one for bets.

The card ordering is simple: we compare the cards according to their rank. The hand ordering is implemented according to the spec of the challenge: we first compare the hand types, and if they are equal, we compare the individual cards of the hands.

The bet ordering is then defined in terms of hand ordering.

Calculating the winnings

Given the work we've done so far, calculating the winnings is a matter of sorting the bets and calculating the winnings for each:

def calculateWinnings(bets: List[Bet]): Int =
bets.sorted.zipWithIndex.map { case (bet, index) => bet.bid * (index + 1) }.sum

def parse(input: String): List[Bet] =
input.linesIterator.toList.map(Bet(_))

def part1(input: String): Int =
calculateWinnings(parse(input))

We read the bets from the input string, sort them, and calculate the winnings for each bet.

Part 2 Solution

The second part of the challenge changes the meaning of the J card. Now it's a Joker, which can be used as any card to produce the best hand possible. In practice, it means determining the prevailing card of the hand and becoming that card: such is the winning strategy of using the Joker. Another change in the rules is that now J is the weakest card when used in tiebreaking comparisons.

We can re-use most of the logic of the Part 1 solution. However because of the different set of rules, we need to create an abstraction to describe the rules for each part, then change the hand scoring logic to take the rules abstraction into account.

Rules

We define a Rules trait that encapsulates the rules of the game and implement it for both cases:

trait Rules:
val rankValues: String
val wildcard: Option[Card]

val standardRules = new Rules:
val rankValues = "23456789TJQKA"
val wildcard = None

val jokerRules = new Rules:
val rankValues = "J23456789TQKA"
val wildcard = Some('J')

Comparison

We then need to change the hand type estimation logic to take the rules into account:

object HandType:
def apply(hand: Hand)(using rules: Rules): HandType =
val cardCounts: Map[Card, Int] =
hand.groupBy(identity).mapValues(_.length).toMap

val cardGroups: List[Int] = rules.wildcard match
case Some(card) if cardCounts.keySet.contains(card) =>
val wildcardCount = cardCounts(card)
val cardGroupsNoWildcard = cardCounts.removed(card).values.toList.sorted.reverse
cardGroupsNoWildcard match
case Nil => List(wildcardCount)
case _ => cardGroupsNoWildcard.head + wildcardCount :: cardGroupsNoWildcard.tail
case _ => cardCounts.values.toList.sorted.reverse

cardGroups match
case 5 :: _ => HandType.FiveOfAKind
case 4 :: _ => HandType.FourOfAKind
case 3 :: 2 :: Nil => HandType.FullHouse
case 3 :: _ => HandType.ThreeOfAKind
case 2 :: 2 :: _ => HandType.TwoPair
case 2 :: _ => HandType.OnePair
case _ => HandType.HighCard
end apply
end HandType

The logic is the same as in the Part 1 solution, except that now we need to take the wildcard into account. If the wildcard is present in the hand, we need to calculate the hand type as if the wildcard was not present, and then add the wildcard count to the largest group of cards. If the wildcard is not present, we calculate the hand type as before. We also handle the case when the hand is composed entirely of wildcards.

We then need to change the card comparison logic to also depend on the rules:

given cardOrdering(using rules: Rules): Ordering[Card] = Ordering.by(rules.rankValues.indexOf(_))

The rest of the orderings stay the same, except we need to make them also depend on the Rules as they all use cardOrdering in some way:

given handOrdering(using Rules): Ordering[Hand] = (h1: Hand, h2: Hand) =>
val h1Type = HandType(h1)
val h2Type = HandType(h2)
if h1Type != h2Type then h1Type.ordinal - h2Type.ordinal
else h1.zip(h2).find(_ != _).map( (c1, c2) => cardOrdering.compare(c1, c2) ).getOrElse(0)
given betOrdering(using Rules): Ordering[Bet] = Ordering.by(_.hand)

Calculating the winnings

The winnings calculation also stays the same, except for the addition of the Rules parameter, which is required for sorting the bets.

def calculateWinnings(bets: List[Bet])(using Rules): Int =
bets.sorted.zipWithIndex.map { case (bet, index) => bet.bid * (index + 1) }.sum

Finally, we can calculate the winnings as before while specifying the rules under which to do the calculation:

def part2(input: String): Int =
calculateWinnings(parse(input))(using jokerRules)

Complete Code

type Card = Char
type Hand = String

case class Bet(hand: Hand, bid: Int)
object Bet:
def apply(s: String): Bet = Bet(s.take(5), s.drop(6).toInt)

enum HandType:
case HighCard, OnePair, TwoPair, ThreeOfAKind, FullHouse, FourOfAKind, FiveOfAKind
object HandType:
def apply(hand: Hand)(using rules: Rules): HandType =
val cardCounts: Map[Card, Int] =
hand.groupBy(identity).mapValues(_.length).toMap

val cardGroups: List[Int] = rules.wildcard match
case Some(card) if cardCounts.keySet.contains(card) =>
val wildcardCount = cardCounts(card)
val cardGroupsNoWildcard = cardCounts.removed(card).values.toList.sorted.reverse
cardGroupsNoWildcard match
case Nil => List(wildcardCount)
case _ => cardGroupsNoWildcard.head + wildcardCount :: cardGroupsNoWildcard.tail
case _ => cardCounts.values.toList.sorted.reverse

cardGroups match
case 5 :: _ => HandType.FiveOfAKind
case 4 :: _ => HandType.FourOfAKind
case 3 :: 2 :: Nil => HandType.FullHouse
case 3 :: _ => HandType.ThreeOfAKind
case 2 :: 2 :: _ => HandType.TwoPair
case 2 :: _ => HandType.OnePair
case _ => HandType.HighCard
end apply
end HandType

trait Rules:
val rankValues: String
val wildcard: Option[Card]

val standardRules = new Rules:
val rankValues = "23456789TJQKA"
val wildcard = None

val jokerRules = new Rules:
val rankValues = "J23456789TQKA"
val wildcard = Some('J')


given cardOrdering(using rules: Rules): Ordering[Card] = Ordering.by(rules.rankValues.indexOf(_))
given handOrdering(using Rules): Ordering[Hand] = (h1: Hand, h2: Hand) =>
val h1Type = HandType(h1)
val h2Type = HandType(h2)
if h1Type != h2Type then h1Type.ordinal - h2Type.ordinal
else h1.zip(h2).find(_ != _).map( (c1, c2) => cardOrdering.compare(c1, c2) ).getOrElse(0)
given betOrdering(using Rules): Ordering[Bet] = Ordering.by(_.hand)

def calculateWinnings(bets: List[Bet])(using Rules): Int =
bets.sorted.zipWithIndex.map { case (bet, index) => bet.bid * (index + 1) }.sum

def parse(input: String): List[Bet] =
input.linesIterator.toList.map(Bet(_))

def part1(input: String): Int =
println(calculateWinnings(parse(input))(using standardRules))

def part2(input: String): Int =
println(calculateWinnings(parse(input))(using jokerRules))

Solutions from the community

Share your solution to the Scala community by editing this page.

- + \ No newline at end of file diff --git a/2023/puzzles/day08/index.html b/2023/puzzles/day08/index.html index bcb089fe2..ad9bd3f67 100644 --- a/2023/puzzles/day08/index.html +++ b/2023/puzzles/day08/index.html @@ -5,7 +5,7 @@ Day 8: Haunted Wasteland | Scala Center Advent of Code - + @@ -14,7 +14,7 @@ The transition function needs to know the network it is operating on. To be a bit more flexible I decided to create a function that returns the transition function based on a given network.

def transitions(network: Map[String, Vector[String]]): Transition =
(n, d) =>
d match
case Instr.GoLeft => network(n)(0)
case Instr.GoRight => network(n)(1)

For the predicate tell the function to stop when STATE == "ZZZ"

def part1(input: String): Int =
val inpL = input.split("\n\n")
val instructions = Instr.parse(inpL.head)
val network = parseNetwork(inpL.tail.head.split("\n").toList)
val trans = transitions(network)

countStepsUntil("AAA", instructions, trans, 0, _ == "ZZZ")

Part two solution

The second part is a bit trickier. We are required to find the number of steps to take, until all nodes in the state end with a Z. One can try to brute force this, by changing the transition function to (Set[String], Instr) => Set[String] but this takes way to much processing time. Key insight comes from the realization that all states in the starting Set[Sate] move on their own independent path and keep repeating themselves. By knowing this we can use an LCM to get to the correct answer.

def part2(input: String): Long =
// ... reuse parsing from part 1
def lcm(a: Long, b: Long): Long =
a * b / gcd(a, b)

def gcd(a: Long, b: Long): Long =
if b == 0 then a else gcd(b, a % b)

// get all the starting states
val starts: Set[State] = network.keySet.filter(_.endsWith("A"))

starts
.map(state =>
// for each state find the cycle time
countStepsUntil(
state, instructions, trans, 0, _.endsWith("Z")).toLong)
.reduce(lcm)

final code

import scala.annotation.tailrec

type State = String

type Transition = (State, Instr) => State

enum Instr:
case GoLeft, GoRight

object Instr:
def parse(inp: String): LazyList[Instr] =
inp
.map {
case 'L' => Instr.GoLeft
case 'R' => Instr.GoRight
}
.to(LazyList) #::: Instr.parse(inp)

def parseNetwork(inp: List[String]): Map[String, Vector[String]] =
inp.map {
case s"$a = ($b, $c)" => (a -> Vector(b, c))
}.toMap

def transitions(network: Map[String, Vector[String]]): Transition =
(n, d) =>
d match
case Instr.GoLeft => network(n)(0)
case Instr.GoRight => network(n)(1)

@tailrec
def countStepsUntil(
state: State, instrs: LazyList[Instr], trans: Transition,
count: Int, pred: State => Boolean): Int =
if pred(state) then count
else
countStepsUntil(
trans(state, instrs.head), instrs.tail, trans, count + 1, pred)

def part1(input: String): Int =
val inpL = input.split("\n\n")
val instructions = Instr.parse(inpL.head)
val network = parseNetwork(inpL.tail.head.split("\n").toList)
val trans = transitions(network)

countStepsUntil("AAA", instructions, trans, 0, _ == "ZZZ")

def part2(input: String): Long =
val inpL = input.split("\n\n")
val instructions = Instr.parse(inpL.head)
val network = parseNetwork(inpL.tail.head.split("\n").toList)
val trans = transitions(network)

val starts: Set[State] = network.keySet.filter(_.endsWith("A"))

def lcm(a: Long, b: Long): Long =
a * b / gcd(a, b)

def gcd(a: Long, b: Long): Long =
if b == 0 then a else gcd(b, a % b)

starts
.map(state =>
countStepsUntil(
state, instructions, trans, 0, _.endsWith("Z")).toLong)
.reduce(lcm)

Solutions from the community

Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

- + \ No newline at end of file diff --git a/2023/puzzles/day09/index.html b/2023/puzzles/day09/index.html index b38b4410b..07f26b48a 100644 --- a/2023/puzzles/day09/index.html +++ b/2023/puzzles/day09/index.html @@ -5,7 +5,7 @@ Day 9: Mirage Maintenance | Scala Center Advent of Code - + @@ -45,7 +45,7 @@ suggests "Adding the new values on the left side of each sequence from bottom to top", and this suggestion can be turned into code.

Solutions from the community

Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

- + \ No newline at end of file diff --git a/2023/puzzles/day10/index.html b/2023/puzzles/day10/index.html index d62dd36d5..e71d25879 100644 --- a/2023/puzzles/day10/index.html +++ b/2023/puzzles/day10/index.html @@ -5,7 +5,7 @@ Day 10: Pipe Maze | Scala Center Advent of Code - + @@ -30,7 +30,7 @@ and only increase the count in enclosed portions for tiles which are not part of the loop. Finally, we obtain the total number of enclosed tiles by iterating over all lines.

def part2(input: String): Int =
val grid = parse(input)
val inLoop = findLoop(grid).toSet

def connectsNorth(i: Int, j: Int): Boolean =
connected(grid)(i,j).contains(i-1, j)

def enclosedInLine(i: Int): Int =
val (_, count) = grid(i).indices.foldLeft((false, 0)):
case ((enclosed, count), j) if inLoop(i, j) =>
(enclosed ^ connectsNorth(i, j), count)
case ((true, count), j) =>
(true, count + 1)
case ((false, count), j) =>
(false, count)
count

grid.indices.map(enclosedInLine).sum

Final Code

def parse(input: String) = input.linesIterator.toSeq

/** The tiles connected to point `p` in the `grid` */
def connected(grid: Seq[String])(p: (Int, Int)): Set[(Int, Int)] =
val (i, j) = p
grid(i)(j) match
case '|' => Set((i - 1, j), (i + 1, j))
case '-' => Set((i, j - 1), (i, j + 1))
case 'L' => Set((i - 1, j), (i, j + 1))
case 'J' => Set((i - 1, j), (i, j - 1))
case '7' => Set((i + 1, j), (i, j - 1))
case 'F' => Set((i + 1, j), (i, j + 1))
case '.' => Set()
case 'S' => Set((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1))
.filter((i, j) => grid.isDefinedAt(i) && grid(i).isDefinedAt(j))
.filter(connected(grid)(_).contains(i, j))
end connected

/** The loop starting from 'S' in the grid */
def findLoop(grid: Seq[String]): Seq[(Int, Int)] =
val start =
val startI = grid.indexWhere(_.contains('S'))
(startI, grid(startI).indexOf('S'))

val initial = (start, connected(grid)(start).head)

/** List of connected points starting from 'S'
* e.g. `(y0, x0) :: (y1, x1) :: (y2, x2) :: ...`
*/
val loop = LazyList.iterate(initial): (prev, curr) =>
val next = connected(grid)(curr) - prev
(curr, next.head)

start +: loop.map(_._2).takeWhile(_ != start)
end findLoop

def part1(input: String): String =
val grid = parse(input)
val loop = findLoop(grid)
(loop.length / 2).toString
end part1

def part2(input: String): String =
val grid = parse(input)
val inLoop = findLoop(grid).toSet

/** True iff `grid(i)(j)` is a pipe connecting to the north */
def connectsNorth(i: Int, j: Int): Boolean =
connected(grid)(i, j).contains(i - 1, j)

/** Number of tiles enclosed by the loop in `grid(i)` */
def enclosedInLine(i: Int): Int =
val (_, count) = grid(i).indices.foldLeft((false, 0)):
case ((enclosed, count), j) if inLoop(i, j) =>
(enclosed ^ connectsNorth(i, j), count)
case ((true, count), j) =>
(true, count + 1)
case ((false, count), j) =>
(false, count)
count

grid.indices.map(enclosedInLine).sum.toString
end part2

Solutions from the community

Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

- + \ No newline at end of file diff --git a/2023/puzzles/day11/index.html b/2023/puzzles/day11/index.html index 9f79fcd41..f8b999078 100644 --- a/2023/puzzles/day11/index.html +++ b/2023/puzzles/day11/index.html @@ -5,7 +5,7 @@ Day 11: Cosmic Expansion | Scala Center Advent of Code - + @@ -32,7 +32,7 @@ Same with columns. Can we still keep the counting linear?
  • (Squared) Euclidean distance: what if our distance is the square of the actual distance between the #s (i.e. (a.x - b.x)^2 + (a.y - b.y)^2)? We should be able to still keep the counting algorithm linear with some math!
  • Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2023/puzzles/day12/index.html b/2023/puzzles/day12/index.html index 9e33ef5b3..18080f76c 100644 --- a/2023/puzzles/day12/index.html +++ b/2023/puzzles/day12/index.html @@ -5,14 +5,14 @@ Day 12: Hot Springs | Scala Center Advent of Code - +
    Skip to main content

    Day 12: Hot Springs

    by @mbovel

    Puzzle description

    https://adventofcode.com/2023/day/12

    Scaffold

    Let's create a folder with a file day12.scala to hold the core of our code.

    We start by writing two examples and defining three functions countAll, countRow, and count that we will implement later:

    //> using scala 3.3.1

    import scala.io.Source

    /** The example puzzle from the problem description. */
    val examplePuzzle = IArray(
    "???.### 1,1,3",
    ".??..??...?##. 1,1,3",
    "?#?#?#?#?#?#?#? 1,3,1,6",
    "????.#...#... 4,1,1",
    "????.######..#####. 1,6,5",
    "###???????? 3,2,1"
    )

    /** Our personal puzzle input. */
    val personalPuzzle = Source.fromFile("input.txt").mkString.trim()

    /** Entry point for part 1. */
    @main def part1(): Unit = println(countAll(personalPuzzle))

    /** Sums `countRow` over all rows in `input`. */
    def countAll(input: String): Long = ???

    /** Counts all of the different valid arrangements of
    * operational and broken springs in the given row.
    */
    def countRow(input: String): Long = ???

    /** Helper recursive function for `countRow` that does
    * the actual work.
    *
    * @param input
    * the remaining input to process
    * @param ds
    * a list of the numbers of damaged springs remaining to be placed
    */
    def count(input: List[Char], ds: List[Int]): Long = ???

    Thanks to scala-cli we can run this file with:

    $ scala-cli -M part1 .

    Tests

    In the same folder, we create a file day12.test.scala to hold our tests. We write one test for each individual row of the example from the instructions, a test for the whole example, and a test for our personal puzzle input:

    //> using scala 3.3.1
    //> using test.dep org.scalameta::munit::1.0.0-M10

    class Day12Test extends munit.FunSuite:
    test("example row 1"):
    assertEquals(countRow(examplePuzzle(0)), 1L)

    test("example row 2"):
    assertEquals(countRow(examplePuzzle(1)), 4L)

    test("example row 3"):
    assertEquals(countRow(examplePuzzle(2)), 1L)

    test("example row 4"):
    assertEquals(countRow(examplePuzzle(3)), 1L)

    test("example row 5"):
    assertEquals(countRow(examplePuzzle(4)), 4L)

    test("example row 6"):
    assertEquals(countRow(examplePuzzle(5)), 10L)

    test("example"):
    assertEquals(countAll(examplePuzzle.mkString("\n")), 21L)

    test("puzzle input"):
    assertEquals(countAll(personalPuzzle), 7118L)

    We can run the tests with:

    $ scala-cli test .

    Part 1

    Implementation of countAll and countRow

    countAll and countRow can be implemented concisely using split and map:

    def countAll(input: String): Long = input.split("\n").map(countRow).sum

    def countRow(input: String): Long =
    val Array(conditions, damagedCounts) = input.split(" ")
    count(
    conditions.toList,
    damagedCounts.split(",").map(_.toInt).toList
    )

    Character-level implementation of count

    For our first implementation, we'll iterate through the input string character by character, and we'll use an additional parameter d to keep track of the number of consecutive damaged springs seen so far:

    /** Helper recursive function for `countRow` that does the actual work.
    *
    * @param input
    * the remaining input to process
    * @param ds
    * a list of the numbers of damaged springs remaining to be placed
    * @param d
    * the number of consecutive damaged springs seen so far
    */
    def count(input: List[Char], ds: List[Int], d: Int = 0): Long =
    // We've reached the end of the input.
    if input.isEmpty then
    // This is a valid arrangement if there are no sequences of
    // damaged springs left to place (ds.isEmpty) and we're
    // not currently in a sequence of damaged springs (d == 0).
    if ds.isEmpty && d == 0 then 1L
    // This is also a valid arrangement if there is one sequence
    // of damaged springs left to place (ds.length == 1) and its
    // size is d (ds.head == d).
    else if ds.length == 1 && ds.head == d then 1L
    // Otherwise, this is not a valid arrangement.
    else 0
    else
    def operationalCase() =
    // If we're not currently in a sequence of damaged springs,
    // then we can consume an operational spring.
    if d == 0 then count(input.tail, ds, 0)
    // We are currently in a sequence of damaged springs,
    // which this operational spring ends. If the length
    // of the damaged sequence is the expected one, the we can
    // continue with the next damaged sequence.
    else if !ds.isEmpty && ds.head == d then
    count(input.tail, ds.tail, 0)
    // Otherwise, this is not a valid arrangement.
    else 0L
    def damagedCase() =
    // If no damaged springs are expected, then this is not a valid
    // arrangement.
    if ds.isEmpty then 0L
    // Optimization: no need to recurse if d becomes greater than the
    // expected damaged sequence length.
    else if d == ds.head then 0L
    // Otherwise, we can consume a damaged spring.
    else count(input.tail, ds, d + 1)
    input.head match
    // If we encounter a question mark, this position can have
    // either an operational or a damaged spring.
    case '?' => operationalCase() + damagedCase()
    // If we encounter a dot, this position has an operational
    // spring.
    case '.' => operationalCase()
    // If we encounter a hash, this position has damaged spring.
    case '#' => damagedCase()

    Counting calls

    The implementation above is correct, but it has an exponential run time complexity: it calls itself up to two times at each step, so the number of calls grows exponentially with the length of the input.

    To demonstrate this, we will add a counter ops that counts the number of calls to count:

    var ops = 0
    private def count(input: List[Char], d: Long, ds: List[Long]): Long =
    ops += 1
    // ... same as before ...

    And consider the following example puzzle in addition to our two existing examples:

    val slowPuzzleSize = 16
    val slowPuzzle =
    ("??." * slowPuzzleSize) + " " + ("1," * (slowPuzzleSize - 1)) + "1"

    To see how many times count is called for our example puzzles, we add the following function:

    @main def countOps =
    val puzzles =
    IArray(
    ("example", examplePuzzle.mkString("\n")),
    ("personal", personalPuzzle),
    ("slow", slowPuzzle)
    )
    for (name, input) <- puzzles do
    ops = 0
    val start = System.nanoTime()
    val result = countAll(input)
    val end = System.nanoTime()
    val elapsed = (end - start) / 1_000_000
    println(f"$name%8s: $result%5d ($ops%9d calls, $elapsed%4d ms)")

    Running this code gives us the following output:

     example:    21 (      305 calls,   24 ms)
    personal: 7118 ( 149712 calls, 37 ms)
    slow: 65536 (172186881 calls, 1415 ms)

    Memoization

    Many of the calls to count are redundant: they are made with the same arguments as previous calls. A quick way to improve algorithmic complexity and the performance of this function is to memoize it: we can cache the results of previous calls to count and reuse them when the same arguments are passed again.

    We can use a mutable.Map to store the results of previous calls. We use tuples containing the arguments (input, ds, d) as keys, and we use the getOrElseUpdate method to either retrieve the cached result or compute it and store it in the map.

    Here is the memoized version of count:

    import scala.collection.mutable

    val cache = mutable.Map.empty[(List[Char], List[Int], Long), Long]
    private def count(input: List[Char], ds: List[Int], d: Int = 0): Long =
    cache.getOrElseUpdate((input, ds, d), countUncached(input, ds, d))

    var ops = 0
    def countUncached(input: List[Char], ds: List[Int], d: Int = 0): Long =
    ops += 1
    // ... same as before ...

    Running countOps again, we now get the following output:

     example:    21 (      169 calls,   32 ms)
    personal: 7118 ( 38382 calls, 74 ms)
    slow: 65536 ( 679 calls, 1 ms)

    That's much better! The number of operations is lower, and the running time is faster in the pathological slow puzzle case.

    info

    The number of operations is a good primary metric here, because it is completely deterministic, stable across runs and is a good proxy for the complexity of the algorithm.

    We also measure the actual running time of the function as an indicator, but a naive measurement like this is not accurate and can vary a lot between runs. For a more accurate measurement, one could use a benchmarking library such as JMH (for example with the JMH SBT plugin) or ScalaMeter.

    Part 2

    Oh, there is a second part to this puzzle!

    Implementation

    The only change needed to implement the second part is to unfold the input rows before counting them. We add the unfoldRow function to do that, and call it from countAllUnfolded:

    /** Entry point for part 2 */
    @main def part2(): Unit =
    println(countAllUnfolded(personalPuzzle))

    def countAllUnfolded(input: String): Long =
    input.split("\n").map(unfoldRow).map(countRow).sum

    def unfoldRow(input: String): String =
    val Array(conditions, damagedCounts) =
    input.split(" ")
    val conditionsUnfolded =
    (0 until 5).map(_ => conditions).mkString("?")
    val damagedCountUnfolded =
    (0 until 5).map(_ => damagedCounts).mkString(",")
    f"$conditionsUnfolded $damagedCountUnfolded"

    Executing part2 with my personal input puzzle runs in ~800 ms on my machine, and countUncached is called 681'185:

              example:            21 (   169 calls,  31 ms)
    personal: 7118 ( 38382 calls, 74 ms)
    slow: 65536 ( 679 calls, 1 ms)
    personal unfolded: 7030194981795 (681185 calls, 815 ms)

    Can we do better?

    Group-level implementation of count

    Our first implementation of count works. Recursing character by character through the input string looks like a natural way to solve this problem. But we can simplify the implementation and improve its performance by considering groups instead of individual characters.

    To know if a group of damaged springs of length nn can be at a given position, we can consume the next nn characters of the input and check if they can all be damaged springs (i.e. none of them is a .), and if the following character can be an operational spring (i.e. it is not a #).

    import scala.collection.mutable

    extension (b: Boolean) private inline def toLong: Long =
    if b then 1L else 0L

    val cache2 = mutable.Map.empty[(List[Char], List[Int]), Long]

    private def count2(input: List[Char], ds: List[Int]): Long =
    cache2.getOrElseUpdate((input, ds), count2Uncached(input, ds))

    def count2Uncached(input: List[Char], ds: List[Int]): Long =
    ops += 1
    // We've seen all expected damaged sequences. The arrangement
    // is therefore valid only if the input does not contain
    // damaged springs.
    if ds.isEmpty then input.forall(_ != '#').toLong
    // The input is empty but we expected some damaged springs,
    // so this is not a valid arrangement.
    else if input.isEmpty then 0L
    else
    def operationalCase(): Long =
    // We can consume all following operational springs.
    count2(input.tail.dropWhile(_ == '.'), ds)
    def damagedCase(): Long =
    // If the length of the input is less than the expected
    // length of the damaged sequence, then this is not a
    // valid arrangement.
    if input.length < ds.head then 0L
    else
    // Split the input into a group of length ds.head and
    // the rest.
    val (group, rest) = input.splitAt(ds.head)
    // If the group contains any operational springs, then
    // this is not a a group of damaged springs, so this
    // is not a valid arrangement.
    if !group.forall(_ != '.') then 0L
    // If the rest of the input is empty, then this is a
    // valid arrangement only if the damaged sequence is
    // the last one expected.
    else if rest.isEmpty then ds.tail.isEmpty.toLong
    // If we now have a damaged spring, then this is not
    // the end of a damaged sequence as expected, and
    // therefore not a valid arrangement.
    else if rest.head == '#' then 0L
    // Otherwise, we can continue with the rest of the
    // input and the next expected damaged sequence.
    else count2(rest.tail, ds.tail)
    input.head match
    case '?' => operationalCase() + damagedCase()
    case '.' => operationalCase()
    case '#' => damagedCase()

    I find this implementation simpler and easier to understand than the previous one. Do you agree?

    It naturally results in less calls, and the running time is improved:

              example:            21 (    69 calls,   36 ms)
    personal: 7118 ( 12356 calls, 74 ms)
    slow: 65536 ( 404 calls, 1 ms)
    personal unfolded: 7030194981795 (235829 calls, 497 ms)

    Local cache

    We implemented memoization by using a global mutable map. What happens if we use a local, distinct one for each call to count instead?

    import scala.collection.mutable

    def count2(input: List[Char], ds: List[Int]): Long =
    val cache2 = mutable.Map.empty[(List[Char], List[Int]), Long]

    def count2Cached(input: List[Char], ds: List[Int]): Long =
    cache2.getOrElseUpdate((input, ds), count2Uncached(input, ds))

    def count2Uncached(input: List[Char], ds: List[Int]): Long =
    // ... same as before ...
    // (but calling count2Cached instead of count2)

    Even though this results to more calls to count2Uncached, this actually improves the performance of the unfolded version, down to ~400 ms on my machine:

              example:            21 (       71 calls,   32 ms)
    personal: 7118 ( 18990 calls, 67 ms)
    slow: 65536 ( 425 calls, 3 ms)
    personal unfolded: 7030194981795 ( 260272 calls, 407 ms)

    Simplify cache keys

    Because we will always consider the same sublists of input and ds for the lifetime of the cache, we can just use the lengths of these lists as keys:

    import scala.collection.mutable

    def count2(input: List[Char], ds: List[Int]): Long =
    val cache2 = mutable.Map.empty[(Int, Int), Long]

    def count2Cached(input: List[Char], ds: List[Int]): Long =
    val key = (input.length, ds.length)
    cache2.getOrElseUpdate(key, count2Uncached(input, ds))

    // ... def count2Uncached as before

    Which further reduces the running time of the unfolded version to ~320 ms on my machine:

              example:            21 (       71 calls,   33 ms)
    personal: 7118 ( 18990 calls, 66 ms)
    slow: 65536 ( 425 calls, 0 ms)
    personal unfolded: 7030194981795 ( 260272 calls, 320 ms)

    Simplify the cache structure

    Our cache key is now just a pair of integers, so we don't need a Map; an Array can do the job just as well.

    def count2(input: List[Char], ds: List[Int]): Long =
    val dim1 = input.length + 1
    val dim2 = ds.length + 1
    val cache = Array.fill(dim1 * dim2)(-1L)

    def count2Cached(input: List[Char], ds: List[Int]): Long =
    val key = input.length * dim2 + ds.length
    val result = cache(key)
    if result == -1L then
    val result = count2Uncached(input, ds)
    cache(key) = result
    result
    else result

    // ... def count2Uncached as before

    This reduces the running time of the unfolded version down to ~200 ms on my machine:

              example:            21 (       71 calls,   27 ms)
    personal: 7118 ( 18990 calls, 47 ms)
    slow: 65536 ( 425 calls, 0 ms)
    personal unfolded: 7030194981795 ( 260272 calls, 201 ms)

    Inline helper functions

    We have used helper functions to structure the implementation of count2. To avoid the calls overhead, we can use Scala 3's inline keyword.

    After adding the inline modifier to count2Cached, operationalCase and damagedCase, the running time of the unfolded version is reduced to ~140 ms on my machine:

              example:            21 (       71 calls,   28 ms)
    personal: 7118 ( 18990 calls, 50 ms)
    slow: 65536 ( 425 calls, 0 ms)
    personal unfolded: 7030194981795 ( 260272 calls, 137 ms)

    Further optimizations

    • Using a different data structure for the input and the damaged sequence, for example an IArray instead of a List, and indexing into it instead of using splitAt, tail or head methods would probably improve the performance further, but would be more verbose and less idiomatic.
    • Parallelizing countAllUnfolded did not result in any performance improvement on my machine. It might on larger inputs.

    Can you think of other optimizations that could improve the performance of this code without sacrificing readability?

    Final Code

    /** Entry point for part 1. */
    def part1(input: String): Unit =
    println(countAll(input))

    /** Sums `countRow` over all rows in `input`. */
    def countAll(input: String): Long =
    input.split("\n").map(countRow).sum

    /** Counts all of the different valid arrangements
    * of operational and broken springs in the given row.
    */
    def countRow(input: String): Long =
    val Array(conditions, damagedCounts) = input.split(" ")
    count2(
    conditions.toList,
    damagedCounts.split(",").map(_.toInt).toList
    )

    extension (b: Boolean) private inline def toLong: Long =
    if b then 1L else 0L

    def count2(input: List[Char], ds: List[Int]): Long =
    val dim1 = input.length + 1
    val dim2 = ds.length + 1
    val cache = Array.fill(dim1 * dim2)(-1L)

    inline def count2Cached(input: List[Char], ds: List[Int]): Long =
    val key = input.length * dim2 + ds.length
    val result = cache(key)
    if result == -1L then
    val result = count2Uncached(input, ds)
    cache(key) = result
    result
    else result

    def count2Uncached(input: List[Char], ds: List[Int]): Long =
    // We've seen all expected damaged sequences.
    // The arrangement is therefore valid only if the
    // input does not contain damaged springs.
    if ds.isEmpty then input.forall(_ != '#').toLong
    // The input is empty but we expected some damaged springs,
    // so this is not a valid arrangement.
    else if input.isEmpty then 0L
    else
    inline def operationalCase(): Long =
    // Operational case: we can consume all operational
    // springs to get to the next choice.
    count2Cached(input.tail.dropWhile(_ == '.'), ds)
    inline def damagedCase(): Long =
    // If the length of the input is less than the expected
    // length of the damaged sequence, then this is not a
    // valid arrangement.
    if input.length < ds.head then 0L
    else
    // Split the input into a group of length ds.head and
    // the rest.
    val (group, rest) = input.splitAt(ds.head)
    // If the group contains any operational springs, then
    // this is not a a group of damaged springs, so this
    // is not a valid arrangement.
    if !group.forall(_ != '.') then 0L
    // If the rest of the input is empty, then this is a
    // valid arrangement only if the damaged sequence
    // is the last one expected.
    else if rest.isEmpty then ds.tail.isEmpty.toLong
    // If we now have a damaged spring, then this is not the
    // end of a damaged sequence as expected, and therefore
    // not a valid arrangement.
    else if rest.head == '#' then 0L
    // Otherwise, we can continue with the rest of the input
    // and the next expected damaged sequence.
    else count2Cached(rest.tail, ds.tail)
    input.head match
    case '?' => operationalCase() + damagedCase()
    case '.' => operationalCase()
    case '#' => damagedCase()

    count2Cached(input, ds)
    end count2

    /** Entry point for part 2 */
    def part2(input: String): Unit =
    println(countAllUnfolded(input))

    def countAllUnfolded(input: String): Long =
    input.split("\n").map(unfoldRow).map(countRow).sum

    def unfoldRow(input: String): String =
    val Array(conditions, damagedCounts) =
    input.split(" ")
    val conditionsUnfolded =
    (0 until 5).map(_ => conditions).mkString("?")
    val damagedCountUnfolded =
    (0 until 5).map(_ => damagedCounts).mkString(",")
    f"$conditionsUnfolded $damagedCountUnfolded"

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2023/puzzles/day13/index.html b/2023/puzzles/day13/index.html index 68e6c1578..a9d018130 100644 --- a/2023/puzzles/day13/index.html +++ b/2023/puzzles/day13/index.html @@ -5,7 +5,7 @@ Day 13: Point of Incidence | Scala Center Advent of Code - + @@ -14,7 +14,7 @@ This gives a sequence of strings representing the patterns. Then split each pattern by a new line (regex \R). Then for each line we assert that all the characters are valid tiles.

    def parseInput(input: String): Seq[Pattern] =
    val patterns = input.split(raw"\R\R").toSeq
    patterns.map: patternStr =>
    patternStr.split(raw"\R").toSeq.map: lineStr =>
    lineStr.collect[Tile] { case tile: Tile => tile }
    info

    In Scala we tend to prefer a declarative style. An alternative imperative option would be to iterate over each line, accumulating lines into a buffer as we encounter them, and then at each empty line transfer all the accumulated lines as a group to a separate pattern buffer.

    Part 1: detecting pure reflection

    To detect the reflection line in a pattern:

    The resulting code is:

    def findReflection(pattern: Pattern): Option[Int] =
    (1 until pattern.size).find: i =>
    val (leftPart, rightPart) = pattern.splitAt(i)
    leftPart.reverse.zip(rightPart).forall(_ == _)

    If we cannot find a line of reflection, then we transpose the pattern and try to find a column of reflection:

    findReflection(pattern).map(100 * _).orElse(findReflection(pattern.transpose))

    Part 2: detecting the reflection with a unique smudge

    The second part is almost identical to the first part. But, instead of comparing the lines based on equality, we count the number of different characters. We keep the index of the line or column which contains only a single smudge.

    The inner part of findReflection becomes:

    val (leftPart, rightPart) = pattern.splitAt(i)
    val smudges = leftPart.reverse
    .zip(rightPart)
    .map((l1, l2) => l1.zip(l2).count(_ != _))
    .sum
    smudges == 1

    Final code

    type Tile = '.' | '#'
    type Line = Seq[Tile]
    type Pattern = Seq[Line]

    def part1(input: String): Int =
    parseInput(input)
    .flatMap: pattern =>
    findReflection(pattern).map(100 * _).orElse(findReflection(pattern.transpose))
    .sum

    def part2(input: String) =
    parseInput(input)
    .flatMap: pattern =>
    findReflectionWithSmudge(pattern).map(100 * _)
    .orElse(findReflectionWithSmudge(pattern.transpose))
    .sum

    def parseInput(input: String): Seq[Pattern] =
    val patterns = input.split(raw"\R\R").toSeq
    patterns.map: patternStr =>
    patternStr.split(raw"\R").toSeq.map: lineStr =>
    lineStr.collect[Tile] { case tile: Tile => tile }

    def findReflection(pattern: Pattern): Option[Int] =
    (1 until pattern.size).find: i =>
    val (leftPart, rightPart) = pattern.splitAt(i)
    leftPart.reverse.zip(rightPart).forall(_ == _)

    def findReflectionWithSmudge(pattern: Pattern): Option[Int] =
    (1 until pattern.size).find: i =>
    val (leftPart, rightPart) = pattern.splitAt(i)
    val smudges = leftPart.reverse
    .zip(rightPart)
    .map((l1, l2) => l1.zip(l2).count(_ != _))
    .sum
    smudges == 1

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/2023/puzzles/day14/index.html b/2023/puzzles/day14/index.html index 8ad769373..c71c6c101 100644 --- a/2023/puzzles/day14/index.html +++ b/2023/puzzles/day14/index.html @@ -5,14 +5,14 @@ Day 14: Parabolic Reflector Dish | Scala Center Advent of Code - +
    Skip to main content

    Day 14: Parabolic Reflector Dish

    by @anatoliykmetyuk

    Puzzle description

    https://adventofcode.com/2023/day/14

    Part 1 Solution

    Part 1 of the puzzle features a square field where two types of objects can reside: round rocks 'O' and square rocks '#'. The objective is to "tilt" the field north, so that the round rocks roll as far as they can in that direction, while square rocks stay in place. Then, we need to compute the "loading" metric on the northern side of the field which is calculated as a function of how many round rocks there are on the field and how close they are to the northern edge.

    To solve Part 1, we do not even need to simulate the movement of the rocks - that is, we do not need to compute the state of the model of the platform after the tilting was performed. We can iterate from the top (north) of the field to the bottom, one line at a time, and use caching to remember where the rocks can fall. The algorithm is as follows:

    def totalLoading(lines: List[String]): Int =
    var loading = 0
    val whereCanIFall = collection.mutable.Map.empty[Int, Int]
    val totalRows = lines.size
    for
    (line, row) <- lines.zipWithIndex
    (char, col) <- line.zipWithIndex
    do char match
    case 'O' =>
    val fallRow = whereCanIFall.getOrElseUpdate(col, 0)
    loading += totalRows - fallRow
    whereCanIFall(col) = fallRow + 1
    case '#' =>
    whereCanIFall(col) = row + 1
    case '.' =>
    loading

    Part 2 Solution

    Part 2 is much more involved. Here, we are required to tilt the field in all four directions - North, West, South and East - in turn, in many cycles. The objective is to calculate the same loading metric after 1 billion cycles.

    The approach from Part 1 doesn't work here: we now need to modify our model state. The reason we didn't have to do it in Part 1 is that our model evolves in only a single step, and we only need one metric from the end state, so we don't have to calculate the entire final state. In Part 2, however, the model evolves in many steps, and each successive step depends on the previous step. So, we need to calculate the entire final state.

    The Model

    Actually, we already know how to do the Northern tilt - similarly to Part 1. We do not want to re-implement the tilts for the other directions - instead, we want to use the Northern tilt as a building block for the other tilts. So, we need to be able to rotate our model in all four directions, and then tilt it North.

    We can represent the model as a 2D array of chars:

    class Model(state: String):
    private var dataN: Array[Array[Char]] = Array.empty // The array is indexed as dataN(x)(y), where x is the column and y - the row.
    setState(state)

    def setState(newState: String): Unit =
    dataN = newState.split('\n').map(_.toArray).transpose

    We'll need to change the model a lot in a succession of many steps, so we build it with mutability in mind. We parse the input String into the dataN array (N for "North" - the default orientation of the model, against which all the views will be calculated).

    Rotations

    We do not want to actually rotate the model, as in changing the coordinates of the stones in the model array. It is computationally expensive (and this challenge is all about optimization). Instead, we need the ability to calculate a lightweight view of our model, so that the rotation operation is cheap.

    We are going to take a page from computer graphics here. In computer graphics, all transformations of images are defined as matrices, which, when applied to the coordinates of the pixels, produce a new image with changed coordinates. In a computer game, when a player turns, the game doesn't actually rotate the world: instead, it changes the camera transformation matrix, and applies it to the world, thereby calculating what the player sees.

    We are not going to define actual matrices here, but we are going to define a transformation function for each rotation we will be working against. These functions will take a pair of coordinates and will return a new pair of coordinates in a rotated coordinate system:

    type CoordTransform = (Int, Int) => (Int, Int)

    enum Direction:
    case N, W, S, E
    def isVertical: Boolean = this match
    case N | S => true
    case W | E => false

    def mkTransform(direction: Direction, offsetX: Int, offsetY: Int): CoordTransform = direction match
    case Direction.N => (x, y) => (x, y)
    case Direction.W => (x, y) => (offsetY-y, x)
    case Direction.S => (x, y) => (offsetX-x, offsetY-y)
    case Direction.E => (x, y) => (y, offsetX-x)

    def mkInverse(direction: Direction, offsetX: Int, offsetY: Int): CoordTransform = direction match
    case Direction.N => mkTransform(Direction.N, offsetX, offsetY)
    case Direction.W => mkTransform(Direction.E, offsetX, offsetY)
    case Direction.S => mkTransform(Direction.S, offsetX, offsetY)
    case Direction.E => mkTransform(Direction.W, offsetX, offsetY)

    The Direction enum represents the directions in which we are going to rotate the platform. But, if we naively rotate the coordinate system against the origin, we'll end up with some of the coordinates ending up to be negative. It's a design decision really, but in this case, we decide to keep our coordinates positive for better interop with array indexing, the array being the underlying implementation of our model.

    So, not only do we rotate the coordinate system, but we also offset it so that the coordinates are always positive. This is what mkTransform does. mkInverse is a helper function that allows us to rotate the coordinate system back to the original, northern, orientation.

    Then, we are going to teach our model to work with the rotated coordinate system:

    // class Model:
    var rotation = Direction.N
    def extentX = if rotation.isVertical then dataN(0).length else dataN.length
    def extentY = if rotation.isVertical then dataN.length else dataN(0).length
    private def toNorth: CoordTransform = mkInverse(rotation, extentX-1, extentY-1)

    def apply(x: Int, y: Int): Char =
    val (xN, yN) = toNorth(x, y)
    dataN(xN)(yN)

    def update(x: Int, y: Int, char: Char): Unit =
    val (xN, yN) = toNorth(x, y)
    dataN(xN)(yN) = char

    override def toString =
    val sb = new StringBuilder
    for y <- (0 until extentY).toIterator do
    for x <- (0 until extentX).toIterator do
    sb.append(this(x, y))
    sb.append('\n')
    sb.toString

    The rotation of the coordinate system in which the model works is done by assigning the public variable rotation. The extentX and extentY functions return the width and height of the model in the rotated coordinate system. The toNorth function returns a transformation function that converts coordinates from the rotated coordinate system back to the original, northern, coordinate system. This is needed because the dataN array is always in the northern coordinate system.

    The apply and update functions are the getters and setters of the model. They receive coordinates in the rotated coordinate system, and convert them to the northern coordinate system before accessing the dataN array.

    Think of apply and update as optical lenses: the configuration of the lenses (in our case, the rotation variable) can change what you see without changing the object you're looking at.

    Tilting and calculating the loading metric

    Now that we have the ability to rotate the model, we can implement the tilting operation. We only implement it once and it will be usable for all 4 directions:

    def cellsIterator(model: Model): Iterator[(Int, Int, Char)] =
    for
    x <- (0 until model.extentX).toIterator
    y <- (0 until model.extentY).toIterator
    yield (x, y, model(x, y))

    def rollUp(model: Model): Unit =
    val whereCanIFall = collection.mutable.Map.empty[Int, Int]
    for (x, y, c) <- cellsIterator(model) do c match
    case 'O' =>
    val fallY = whereCanIFall.getOrElseUpdate(x, 0)
    model(x, y) = '.'
    model(x, fallY) = 'O'
    whereCanIFall(x) = fallY + 1
    case '#' =>
    whereCanIFall(x) = y + 1
    case '.' =>
    end rollUp

    So, rollUp will always roll the stones up the platform - but the "up" is relative to the rotation we've set! So, if we set the rotation to Direction.W, the stones will roll to the left when we invoke rollUp - although in the current view of the model, it will look like they roll up. If we set the rotation to Direction.S, the stones will roll down. And so on. E.g., to roll left:

    model.rotation = Direction.W
    rollUp(model)

    This is achieved by the cellsIterator method which, under the hood, uses model.extentX, model.extentY and model(x, y) - the dimensions and the model accessor that are relative to the model rotation.

    We can also calculate the model loading as follows:

    def totalLoading(model: Model): Int =
    model.rotation = Direction.N
    var loading = 0
    for (_, y, c) <- cellsIterator(model) do c match
    case 'O' => loading += model.extentY - y
    case _ =>
    loading

    Since the model loading needs to always be calculated against the northern side of the model, we always set the rotation to Direction.N before calculating the loading.

    Naive cycling

    The challenge requires us to cycle through the North-West-South-East tilts for a billion cycles. Let's implement the simplest possible cycling function:

    def cycle(model: Model, times: Int): Unit =
    for i <- 1 to times do
    for cse <- Direction.values do
    model.rotation = cse
    rollUp(model)
    model.rotation = Direction.N

    This simple loop repeats a required number of times, and for each loop, we have a nested loop that iterates over all the directions (in order) and performs the rollup for each of those directions. At the end, the rotation is reset to North.

    Performant cycling

    This solution looks good but won't get to the billion cycles in a reasonable time. The rollups take way too long.

    To optimize, we will use the intent of the operation: we cycle for so many times to eventually converge to a certain state. As the challenge puts it, "This process [cycling repeatedly] should work if you leave it running long enough, but you're still worried about the north support beams...".

    So, there's a possibility that the desired state will be achieved earlier than the billion cycles. Looks like a good case for a dynamic programming approach: we need to remember the states of the model we've seen before and what they look like after one cycle. And if the current state is in our cache, no need to compute the next state again.

    Furthermore, since the transitions between states are deterministic (a state A always leads to state B), the moment one state in our cache is followed by another, previously encountered, state from that cache, we can stop cycling and just calculate the final state from the cache.

    import scala.util.boundary, boundary.break

    def cycle(model: Model, times: Int): Unit =
    val chain = collection.mutable.ListBuffer.empty[String]
    var currentState = model.toString
    boundary:
    for cyclesDone <- 0 until times do
    if chain.contains(currentState) then
    val cycleStart = chain.indexOf(currentState)
    val cycleLength = chain.length - cycleStart
    val cycleIndex = (times - cyclesDone) % cycleLength
    currentState = chain(cycleIndex + cycleStart)
    model.setState(currentState)
    break()

    chain += currentState
    for cse <- Direction.values do
    model.rotation = cse
    rollUp(model)
    currentState = model.toString

    Complete Code

    //> using scala "3.3.1"

    import scala.util.boundary, boundary.break

    type CoordTransform = (Int, Int) => (Int, Int)

    enum Direction:
    case N, W, S, E
    def isVertical: Boolean = this match
    case N | S => true
    case W | E => false

    def mkTransform(direction: Direction, offsetX: Int, offsetY: Int): CoordTransform = direction match
    case Direction.N => (x, y) => (x, y)
    case Direction.W => (x, y) => (offsetY-y, x)
    case Direction.S => (x, y) => (offsetX-x, offsetY-y)
    case Direction.E => (x, y) => (y, offsetX-x)

    def mkInverse(direction: Direction, offsetX: Int, offsetY: Int): CoordTransform = direction match
    case Direction.N => mkTransform(Direction.N, offsetX, offsetY)
    case Direction.W => mkTransform(Direction.E, offsetX, offsetY)
    case Direction.S => mkTransform(Direction.S, offsetX, offsetY)
    case Direction.E => mkTransform(Direction.W, offsetX, offsetY)

    class Model(state: String):
    private var dataN: Array[Array[Char]] = Array.empty // The array is indexed as dataN(x)(y), where x is the column and y - the row.
    setState(state)

    var rotation = Direction.N
    def extentX = if rotation.isVertical then dataN(0).length else dataN.length
    def extentY = if rotation.isVertical then dataN.length else dataN(0).length
    private def toNorth: CoordTransform = mkInverse(rotation, extentX-1, extentY-1)

    def apply(x: Int, y: Int): Char =
    val (xN, yN) = toNorth(x, y)
    dataN(xN)(yN)

    def update(x: Int, y: Int, char: Char): Unit =
    val (xN, yN) = toNorth(x, y)
    dataN(xN)(yN) = char

    def setState(newState: String): Unit =
    dataN = newState.split('\n').map(_.toArray).transpose

    override def toString =
    val sb = new StringBuilder
    for y <- (0 until extentY).toIterator do
    for x <- (0 until extentX).toIterator do
    sb.append(dataN(x)(y))
    sb.append('\n')
    sb.toString
    end Model

    def cellsIterator(model: Model): Iterator[(Int, Int, Char)] =
    for
    x <- (0 until model.extentX).toIterator
    y <- (0 until model.extentY).toIterator
    yield (x, y, model(x, y))

    def rollUp(model: Model): Unit =
    val whereCanIFall = collection.mutable.Map.empty[Int, Int]
    for (x, y, c) <- cellsIterator(model) do c match
    case 'O' =>
    val fallY = whereCanIFall.getOrElseUpdate(x, 0)
    model(x, y) = '.'
    model(x, fallY) = 'O'
    whereCanIFall(x) = fallY + 1
    case '#' =>
    whereCanIFall(x) = y + 1
    case '.' =>
    end rollUp

    def cycle(model: Model, times: Int): Unit =
    val chain = collection.mutable.ListBuffer.empty[String]
    var currentState = model.toString
    boundary:
    for cyclesDone <- 0 until times do
    if chain.contains(currentState) then
    val cycleStart = chain.indexOf(currentState)
    val cycleLength = chain.length - cycleStart
    val cycleIndex = (times - cyclesDone) % cycleLength
    currentState = chain(cycleIndex + cycleStart)
    model.setState(currentState)
    break()

    chain += currentState
    for cse <- Direction.values do
    model.rotation = cse
    rollUp(model)
    currentState = model.toString

    def debug(model: Model): Unit =
    println(s"=== ${model.rotation}; W: ${ model.extentX }, H: ${ model.extentY } ===")
    println(model)

    def totalLoading(model: Model): Int =
    model.rotation = Direction.N
    var loading = 0
    for (_, y, c) <- cellsIterator(model) do c match
    case 'O' => loading += model.extentY - y
    case _ =>
    loading

    def part1(input: String): Int =
    val model = Model(input)
    rollUp(model)
    totalLoading(model)

    def part2(input: String): Int =
    val model = Model(input)
    cycle(model, 1_000_000_000)
    totalLoading(model)

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2023/puzzles/day15/index.html b/2023/puzzles/day15/index.html index bee363437..aeb59e393 100644 --- a/2023/puzzles/day15/index.html +++ b/2023/puzzles/day15/index.html @@ -5,7 +5,7 @@ Day 15: Lens Library | Scala Center Advent of Code - + @@ -18,7 +18,7 @@ We then define our boxes as an array of 256 lists of LabeledLenses:

    /** A labeled lens, as found in the boxes. */
    final case class LabeledLens(label: String, focalLength: Int)

    val boxes = Array.fill[List[LabeledLens]](256)(Nil)

    We then implement the logical operations removeLens and addLens, corresponding to the - and = steps.

    // Remove the lens with the given label from the box it belongs to
    def removeLens(label: String): Unit =
    val boxIndex = hash(label)
    boxes(boxIndex) = boxes(boxIndex).filter(_.label != label)

    // Add a lens in the contents of a box; replace an existing label or add to the end
    def addLensToList(lens: LabeledLens, list: List[LabeledLens]): List[LabeledLens] =
    list match
    case Nil => lens :: Nil // add to the end
    case LabeledLens(lens.label, _) :: tail => lens :: tail // replace
    case head :: tail => head :: addLensToList(lens, tail) // keep looking

    // Add a lens with the given label and focal length into the box it belongs to, in the right place
    def addLens(label: String, focalLength: Int): Unit =
    val lens = LabeledLens(label, focalLength)
    val boxIndex = hash(label)
    boxes(boxIndex) = addLensToList(lens, boxes(boxIndex))

    Finally, we use our trust s extractor to parse and "execute" each step of the initialization sequence:

    // Parse and execute the steps
    for step <- steps do
    step match
    case s"$label-" => removeLens(label)
    case s"$label=$focalLength" => addLens(label, focalLength.toInt)

    To prove to our hash table follows the correct algorithm, we are asked to compute the focusing power of our boxes. Here again, we follow the definition of the problem 1 to 1:

    // Focusing power of a lens in a given box and at a certain position within that box
    def focusingPower(boxIndex: Int, lensIndex: Int, lens: LabeledLens): Int =
    (boxIndex + 1) * (lensIndex + 1) * lens.focalLength

    // Focusing power of all the lenses
    val focusingPowers =
    for
    (box, boxIndex) <- boxes.zipWithIndex
    (lens, lensIndex) <- box.zipWithIndex
    yield
    focusingPower(boxIndex, lensIndex, lens)

    // Sum it up
    val result = focusingPowers.sum

    Final Code

    /** The `HASH` function. */
    def hash(sequence: String): Int =
    sequence.foldLeft(0) { (prev, c) =>
    ((prev + c.toInt) * 17) % 256
    }
    end hash

    /** Parses the input into a list of sequences. */
    def inputToSequences(input: String): List[String] =
    input.filter(_ != '\n').split(',').toList

    def part1(input: String): String =
    val sequences = inputToSequences(input)
    val result = sequences.map(hash(_)).sum
    println(result)
    result.toString()
    end part1

    /** A labeled lens, as found in the boxes. */
    final case class LabeledLens(label: String, focalLength: Int)

    def part2(input: String): String =
    val steps = inputToSequences(input)

    val boxes = Array.fill[List[LabeledLens]](256)(Nil)

    // --- Processing all the steps --------------------

    // Remove the lens with the given label from the box it belongs to
    def removeLens(label: String): Unit =
    val boxIndex = hash(label)
    boxes(boxIndex) = boxes(boxIndex).filter(_.label != label)

    // Add a lens in the contents of a box; replace an existing label or add to the end
    def addLensToList(lens: LabeledLens, list: List[LabeledLens]): List[LabeledLens] =
    list match
    case Nil => lens :: Nil // add to the end
    case LabeledLens(lens.label, _) :: tail => lens :: tail // replace
    case head :: tail => head :: addLensToList(lens, tail) // keep looking

    // Add a lens with the given label and focal length into the box it belongs to, in the right place
    def addLens(label: String, focalLength: Int): Unit =
    val lens = LabeledLens(label, focalLength)
    val boxIndex = hash(label)
    boxes(boxIndex) = addLensToList(lens, boxes(boxIndex))

    // Parse and execute the steps
    for step <- steps do
    step match
    case s"$label-" => removeLens(label)
    case s"$label=$focalLength" => addLens(label, focalLength.toInt)

    // --- Computing the focusing power --------------------

    // Focusing power of a lens in a given box and at a certain position within that box
    def focusingPower(boxIndex: Int, lensIndex: Int, lens: LabeledLens): Int =
    (boxIndex + 1) * (lensIndex + 1) * lens.focalLength

    // Focusing power of all the lenses
    val focusingPowers =
    for
    (box, boxIndex) <- boxes.zipWithIndex
    (lens, lensIndex) <- box.zipWithIndex
    yield
    focusingPower(boxIndex, lensIndex, lens)

    // Sum it up
    val result = focusingPowers.sum
    result.toString()
    end part2

    Run it in the browser

    Part 1

    Part 2

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2023/puzzles/day16/index.html b/2023/puzzles/day16/index.html index 267a1284d..ee42c3219 100644 --- a/2023/puzzles/day16/index.html +++ b/2023/puzzles/day16/index.html @@ -5,14 +5,14 @@ Day 16: The Floor Will Be Lava | Scala Center Advent of Code - +
    Skip to main content

    Day 16: The Floor Will Be Lava

    By @iusildra

    Puzzle description

    https://adventofcode.com/2023/day/16

    Solution summary

    The solution models the input as a grid with 3 types of cells:

    • Empty cells, which are traversable
    • Mirror cells, redirecting the lava flow in a 90° angle
    • Splitter cells, redirecting the lava flow only if it comes from a specific direction, otherwise it just flows through

    Then once we have the model with some helper functions, we can solve the problem by simulating the lava flow.

    1. We start by defining the origin of the lava flow
    2. Then we find the next cell the lava will flow to
      1. If the cell is empty, we move the lava there
      2. If the cell is a mirror, we redirect the lava flow
      3. If the cell is a splitter, we split the flow if necessary
    3. With the new lava flow (and its new direction), we repeat step 2 until we every path hits a wall

    Detailed solution explanation

    Global model

    We start by defining the direction of the lava flow, which is a simple enum, and the coordinates of a cell (a case class):

    enum Direction:
    case Up, Right, Down, Left

    case class Coord(x: Int, y: Int)

    Then, we model the 3 kinds of cells. We need at least a position and a method to compute the next direction(s). For convenience, we'll also add methods to calculate the path to another cell / coordinate.

    Even though a mirror can only "create" 1 new direction, because of splitters, we'll return a list of directions to limit code duplication.

    sealed abstract class Element:
    val pos: Coord
    def nextDirection(comingFrom: Direction): List[Direction]
    def pathTo(coord: Coord): Seq[Coord] =
    if pos.x == coord.x then
    if pos.y < coord.y then (pos.y to coord.y).map(Coord(pos.x, _))
    else (coord.y to pos.y).map(Coord(pos.x, _))
    else if (pos.x < coord.x) then (pos.x to coord.x).map(Coord(_, pos.y))
    else (coord.x to pos.x).map(Coord(_, pos.y))

    object Element:
    def apply(sym: Char, x: Int, y: Int) =
    sym match
    case '\\' => BackslashMirror(Coord(x, y))
    case '/' => SlashMirror(Coord(x, y))
    case '|' => VSplitter(Coord(x, y))
    case '-' => HSplitter(Coord(x, y))
    case _ => throw new IllegalArgumentException

    A mirror redirects the lava flow by 90°, so we need to know where the lava is coming to to know where it will go next. (A lava flow coming to the right will go up with a /-mirror...)

    case class SlashMirror(override val pos: Coord) extends Element:
    def nextDirection(goingTo: Direction) =
    goingTo match
    case Direction.Up => List(Direction.Right)
    case Direction.Left => List(Direction.Down)
    case Direction.Right => List(Direction.Up)
    case Direction.Down => List(Direction.Left)

    case class BackslashMirror(override val pos: Coord) extends Element:
    def nextDirection(goingTo: Direction) =
    goingTo match
    case Direction.Up => List(Direction.Left)
    case Direction.Right => List(Direction.Down)
    case Direction.Down => List(Direction.Right)
    case Direction.Left => List(Direction.Up)

    A splitter redirects the lava flow only if it encounters perpendicularly. Otherwise, it just lets the lava flow through.

    case class VSplitter(pos: Coord) extends Element:
    def nextDirection(goingTo: Direction) =
    goingTo match
    case d @ (Direction.Up | Direction.Down) => List(d)
    case _ => List(Direction.Up, Direction.Down)
    case class HSplitter(pos: Coord) extends Element:
    def nextDirection(comingFrom: Direction) =
    comingFrom match
    case d @ (Direction.Left | Direction.Left) => List(d)
    case _ => List(Direction.Left, Direction.Right)

    Finally, an empty cell has no behavior and shouldn't be traversed in this implementation.

    case class Empty(override val pos: Coord) extends Element:
    def nextDirection(comingFrom: Direction): Nothing =
    throw new UnsupportedOperationException

    Now that we have the model, we can parse the input and create a sparse grid of cells.

    info

    Beware of terminology, a sparse collection is a collection that is optimised for representing a few non-empty elements in a mostly empty space. A sparse collection is useful because when searching for the next cell, we can just look at the next/previous element in the collection instead of iterating and skipping-over empty elements.

    To do so, we need to map over each line with their index (to get the y coordinate) and for each character of a line, if it is not an empty cell, we create the corresponding element.

    def findElements(source: Array[String]): Array[IndexedSeq[Element]] =
    source.zipWithIndex
    .map: (line, y) =>
    line.zipWithIndex
    .filter(_._1 != '.')
    .map { (sym, x) => Element(sym, x, y) }

    Now we have everything we need to solve the problem. Until the end, every piece of code will be in a single method called solution, for convenience (I don't need to pass several arguments to my helper functions). The solver needs to know the input, but also the starting point of the lava flow as well as its direction (which can be ambiguous if it starts on a corner).

    def solution(input: Array[String], origin: Coord, dir: Direction) =

    Then, we'll use some more memory to have faster access to the elements and avoid recomputing the same path several times.

    • elements is a sparse grid of elements (only used as an intermediate step)
    • elementsByRow is a map of y coordinates to the elements on that row, to quickly to find the next cell in the same row
    • elementsByColumn is a map of x coordinates to the elements on that column, to quickly to find the next cell in the same column
    • Since we have a sparse collection, the coordinates of the elements to not match the coordinates of the input, so we need to find the min/max x and y values of the elements to know when to stop the simulation
    • activated is a grid of booleans to know if a cell has already been activated by the lava flow. Note: Array is a mutable type
      // still in the solution method
    val elements = findElements(input)
    val elementsByRow = elements.flatten.groupBy(_.pos.y)
    val elementsByColumn = elements.flatten.groupBy(_.pos.x)
    val minY = elementsByColumn.map((k, v) => (k, v(0).pos.y))
    val maxY = elementsByColumn.map((k, v) => (k, v.last.pos.y))
    val minX = elementsByRow.map((k, v) => (k, v(0).pos.x))
    val maxX = elementsByRow.map((k, v) => (k, v.last.pos.x))
    val activated = Array.fill(input.length)(Array.fill(input(0).length())(false))

    To find the next element in the lava flow, we only need the current element and the direction of the lava flow. But since we are using sparse collections, we cannot just check if x > 0 or x < line.size. An input's line can have 10 elements but only 4 non-Empty ones, so calling the 5-th element would crash with an IndexOutOfBoundsExceptions.

    Yet, this constraint comes with a benefit, we can just check if the next element is in the collection or not, and "jump" to it if it is. If it is not, we can just return an Empty cell (which will later be used to stop the simulation)

      // still in the solution method
    def findNext(
    elem: Element,
    goingTo: Direction
    ): Element =
    goingTo match
    case Direction.Left if elem.pos.x > minX(elem.pos.y) =>
    val byRow = elementsByRow(elem.pos.y)
    byRow(byRow.indexOf(elem) - 1)
    case Direction.Left =>
    Empty(Coord(0, elem.pos.y))
    case Direction.Right if elem.pos.x < maxX(elem.pos.y) =>
    val byRow = elementsByRow(elem.pos.y)
    byRow(byRow.indexOf(elem) + 1)
    case Direction.Right =>
    Empty(Coord(input(0).length() - 1, elem.pos.y))
    case Direction.Up if elem.pos.y > minY(elem.pos.x) =>
    val byCol = elementsByColumn(elem.pos.x)
    byCol(byCol.indexOf(elem) - 1)
    case Direction.Up =>
    Empty(Coord(elem.pos.x, 0))
    case Direction.Down if elem.pos.y < maxY(elem.pos.x) =>
    val byCol = elementsByColumn(elem.pos.x)
    byCol(byCol.indexOf(elem) + 1)
    case Direction.Down =>
    Empty(Coord(elem.pos.x, input.length - 1))

    Also, we might use a method to activate the cells:

      // still in the solution method
    def activate(from: Element, to: Coord) =
    from
    .pathTo(to)
    .foreach:
    case Coord(x, y) => activated(y)(x) = true

    Time to simulate the lava flow. We'll use a recursive method, but there are some caveats:

    • We'll use tail-recursion call to be stack-safe, but with one splitters giving multiple directions, we need to go over one, then over the second etc... which it not tail-recursive.
    • We need to keep a record of all the cells we've visited, and from where we came from, to avoid recomputing the same path several times. (Also called memoization)

    The first caveat can easily be solved by using a Queue (same idea as in the breadth-first search algorithm) to store the next cells to visit. This way when encountering an element giving us multiple directions, we'll just enqueue them and visit them later.

    The second one is a bit less straightforward. We need to be sure that our store won't prevent us from visiting a cell. For instance, with the following input:

    ...vv...
    ...vv...
    ../vv/..
    ...vv...

    Coming from the top of the right / mirror, we must be able to reach the left / mirror. One solution is to store the tuple of source cell and destination cell using a Set (for efficient search among unindexed elements)

    The resulting method looks like this:

      // still in the solution method
    @tailrec // to let the compiler warn us if it's not tail-recursive
    def loop(
    elems: Queue[(Element, Direction)],
    memo: Set[(Coord, Coord)]
    ): Unit =
    if elems.isEmpty then ()
    else elems.dequeue match
    case ((_: Empty, _), _) => throw new UnsupportedOperationException
    case ((elem, goingTo), rest) =>
    val nextElems =
    elem
    .nextDirection(goingTo)
    .foldLeft((rest, memo)): (acc, dir) =>
    val followup = findNext(elem, dir)
    if (memo.contains((elem.pos, followup.pos))) then acc
    else
    activate(elem, followup.pos)
    followup match
    case Empty(pos) => (acc._1, acc._2 + ((elem.pos, pos)))
    case next =>
    (acc._1.enqueue(next -> dir), acc._2 + ((elem.pos, followup.pos)))
    loop(nextElems._1, nextElems._2)
    end loop

    As long as there are elements in the queue, we dequeue and look for the next direction(s). The foldLeft allows us to activate & enqueue the next cells, and to update the memo before passing to the next direction. Once every direction has been explored, we call the method again with the new elements to visit

    Finally, we need to make the first call to the loop method in the solution method. The first element to visit can be computed based on the starting point and the direction of the lava flow. Then we activate the cells on the path and call the loop method.

      // still in the solution method
    val starting = dir match
    case Direction.Right => elementsByRow(origin.y)(0)
    case Direction.Down => elementsByColumn(origin.x)(0)
    case Direction.Left => elementsByRow(origin.y).last
    case Direction.Up => elementsByColumn(origin.x).last

    activate(starting, origin)
    loop(Queue(starting -> dir), Set())

    // println(activated.zipWithIndex.map((line, i) => f"$i%03d " + line.map(if _ then '#' else '.').mkString).mkString("\n"))
    activated.flatten.count(identity)
    end solution

    Once the simulation is done, and all the cells have been activated, we just need to count the number of activated cells. (there is a println commented out to see the lava flow)

    Part 1

    For the first part, we just need to call the solution method with the starting point and the direction of the lava flow

    def part1(input: String) =
    solution(input.split("\n"), Coord(0, 0), Direction.Right)

    Part 2

    Here we need to find the starting point and direction that maximize the number of activated cells. To do so, we'll just try every possible combination and keep the best one.

    def part2(input: String) =
    val lines = input.split("\n")
    val horizontal = (0 until lines.length).flatMap: i =>
    List(
    (Coord(0, i), Direction.Right),
    (Coord(lines(0).length() - 1, i), Direction.Left)
    )
    val vertical = (0 until lines(0).length()).flatMap: i =>
    List(
    (Coord(i, 0), Direction.Down),
    (Coord(i, lines.length - 1), Direction.Up)
    )
    val borders = horizontal ++ vertical
    borders.map((coord, dir) => solution(lines, coord, dir)).max

    Full code

    import scala.annotation.tailrec
    import scala.collection.immutable.Queue
    import scala.collection.mutable.Buffer

    /* -------------------------------------------------------------------------- */
    /* Global */
    /* -------------------------------------------------------------------------- */
    enum Direction:
    case Up, Right, Down, Left

    case class Coord(x: Int, y: Int)

    sealed abstract class Element:
    val pos: Coord
    def nextDirection(comingFrom: Direction): List[Direction]
    def pathTo(coord: Coord): Seq[Coord] =
    if pos.x == coord.x then
    if pos.y < coord.y then (pos.y to coord.y).map(Coord(pos.x, _))
    else (coord.y to pos.y).map(Coord(pos.x, _))
    else if (pos.x < coord.x) then (pos.x to coord.x).map(Coord(_, pos.y))
    else (coord.x to pos.x).map(Coord(_, pos.y))

    object Element:
    def apply(sym: Char, x: Int, y: Int) =
    sym match
    case '\\' => BackslashMirror(Coord(x, y))
    case '/' => SlashMirror(Coord(x, y))
    case '|' => VSplitter(Coord(x, y))
    case '-' => HSplitter(Coord(x, y))
    case _ => throw new IllegalArgumentException

    case class SlashMirror(override val pos: Coord) extends Element:
    def nextDirection(goingTo: Direction) =
    goingTo match
    case Direction.Up => List(Direction.Right)
    case Direction.Left => List(Direction.Down)
    case Direction.Right => List(Direction.Up)
    case Direction.Down => List(Direction.Left)

    case class BackslashMirror(override val pos: Coord) extends Element:
    def nextDirection(goingTo: Direction) =
    goingTo match
    case Direction.Up => List(Direction.Left)
    case Direction.Right => List(Direction.Down)
    case Direction.Down => List(Direction.Right)
    case Direction.Left => List(Direction.Up)

    case class VSplitter(pos: Coord) extends Element:
    def nextDirection(goingTo: Direction) =
    goingTo match
    case d @ (Direction.Up | Direction.Down) => List(d)
    case _ => List(Direction.Up, Direction.Down)
    case class HSplitter(pos: Coord) extends Element:
    def nextDirection(comingFrom: Direction) =
    comingFrom match
    case d @ (Direction.Left | Direction.Left) => List(d)
    case _ => List(Direction.Left, Direction.Right)

    case class Empty(pos: Coord) extends Element:
    def nextDirection(comingFrom: Direction): Nothing =
    throw new UnsupportedOperationException

    def findElements(source: Array[String]) =
    source.zipWithIndex
    .map: (line, y) =>
    line.zipWithIndex
    .filter(_._1 != '.')
    .map { (sym, x) => Element(sym, x, y) }

    def solution(input: Array[String], origin: Coord, dir: Direction) =
    val elements = findElements(input)
    val elementsByRow = elements.flatten.groupBy(_.pos.y)
    val elementsByColumn = elements.flatten.groupBy(_.pos.x)
    val minY = elementsByColumn.map((k, v) => (k, v(0).pos.y))
    val maxY = elementsByColumn.map((k, v) => (k, v.last.pos.y))
    val minX = elementsByRow.map((k, v) => (k, v(0).pos.x))
    val maxX = elementsByRow.map((k, v) => (k, v.last.pos.x))
    val activated = Array.fill(input.length)(Array.fill(input(0).length())(false))
    // val memo = Set.empty[(Coord, Coord)]
    def findNext(
    elem: Element,
    goingTo: Direction
    ): Element =
    goingTo match
    case Direction.Left if elem.pos.x > minX(elem.pos.y) =>
    val byRow = elementsByRow(elem.pos.y)
    byRow(byRow.indexOf(elem) - 1)
    case Direction.Left =>
    Empty(Coord(0, elem.pos.y))
    case Direction.Right if elem.pos.x < maxX(elem.pos.y) =>
    val byRow = elementsByRow(elem.pos.y)
    byRow(byRow.indexOf(elem) + 1)
    case Direction.Right =>
    Empty(Coord(input(0).length() - 1, elem.pos.y))
    case Direction.Up if elem.pos.y > minY(elem.pos.x) =>
    val byCol = elementsByColumn(elem.pos.x)
    byCol(byCol.indexOf(elem) - 1)
    case Direction.Up =>
    Empty(Coord(elem.pos.x, 0))
    case Direction.Down if elem.pos.y < maxY(elem.pos.x) =>
    val byCol = elementsByColumn(elem.pos.x)
    byCol(byCol.indexOf(elem) + 1)
    case Direction.Down =>
    Empty(Coord(elem.pos.x, input.length - 1))

    def activate(from: Element, to: Coord) =
    from
    .pathTo(to)
    .foreach:
    case Coord(x, y) => activated(y)(x) = true

    @tailrec
    def loop(
    elems: Queue[(Element, Direction)],
    memo: Set[(Coord, Coord)]
    ): Unit =
    if elems.isEmpty then ()
    else
    elems.dequeue match
    case ((_: Empty, _), _) => throw new UnsupportedOperationException
    case ((elem, goingTo), rest) =>
    val nextElems =
    elem
    .nextDirection(goingTo)
    .foldLeft((rest, memo)): (acc, dir) =>
    val followup = findNext(elem, dir)
    if (memo.contains((elem.pos, followup.pos))) then acc
    else
    activate(elem, followup.pos)
    followup match
    case Empty(pos) => (acc._1, acc._2 + ((elem.pos, pos)))
    case next =>
    (acc._1.enqueue(next -> dir), acc._2 + ((elem.pos, followup.pos)))
    loop(nextElems._1, nextElems._2)
    end loop

    val starting = dir match
    case Direction.Right => elementsByRow(origin.y)(0)
    case Direction.Down => elementsByColumn(origin.x)(0)
    case Direction.Left => elementsByRow(origin.y).last
    case Direction.Up => elementsByColumn(origin.x).last

    activate(starting, origin)
    loop(Queue(starting -> dir), Set())

    // println(activated.zipWithIndex.map((line, i) => f"$i%03d " + line.map(if _ then '#' else '.').mkString).mkString("\n"))
    activated.flatten.count(identity)

    /* -------------------------------------------------------------------------- */
    /* Part I */
    /* -------------------------------------------------------------------------- */
    def part1(input: String) =
    solution(input.split("\n"), Coord(0, 0), Direction.Right)

    /* -------------------------------------------------------------------------- */
    /* Part II */
    /* -------------------------------------------------------------------------- */
    def part2(input: String) =
    val lines = input.split("\n")
    val horizontal = (0 until lines.length).flatMap: i =>
    List(
    (Coord(0, i), Direction.Right),
    (Coord(lines(0).length() - 1, i), Direction.Left)
    )
    val vertical = (0 until lines(0).length()).flatMap: i =>
    List(
    (Coord(i, 0), Direction.Down),
    (Coord(i, lines.length - 1), Direction.Up)
    )
    val borders = horizontal ++ vertical
    borders.map((coord, dir) => solution(lines, coord, dir)).max

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2023/puzzles/day17/index.html b/2023/puzzles/day17/index.html index c0c4ecdb5..20a269c64 100644 --- a/2023/puzzles/day17/index.html +++ b/2023/puzzles/day17/index.html @@ -5,7 +5,7 @@ Day 17: Clumsy Crucible | Scala Center Advent of Code - + @@ -17,7 +17,7 @@ It parses the input to a Grid, defining it as a given instance.

    def solve(input: String, next: StateTransform): Int =
    given Grid = loadGrid(input)
    search(next)

    Part 1

    Now we need to model our state transformation restrictions for Part 1. We can typically move straight, left, and right, but we need to make sure our streak while moving straight never exceeds 3:

    // Inside case class State:
    def nextStates(using Grid): List[State] =
    List(straight, turnLeft, turnRight).filter: s =>
    s.pos.inBounds && s.streak <= 3

    This will only ever filter out the forward movement, since moving to the left or right resets the streak to 1.

    We can then call solve with nextStates from our entry point for part1:

    def part1(input: String): Int =
    solve(input, _.nextStates)

    Part 2

    Part 2 is similar, but our streak limit increases to 10. Furthermore, while the streak is less than four, only a forward movement is possible:

    // Inside case class State:
    def nextStates2(using Grid): List[State] =
    if streak < 4 then List(straight)
    else List(straight, turnLeft, turnRight).filter: s =>
    s.pos.inBounds && s.streak <= 10

    And we call solve with nextStates2 to solve part2:

    def part2(input: String): Int =
    solve(input, _.nextStates2)

    Final Code

    import collection.mutable.{PriorityQueue, Map}

    def part1(input: String): Int =
    solve(input, _.nextStates)

    def part2(input: String): Int =
    solve(input, _.nextStates2)

    def loadGrid(input: String): Grid =
    Grid:
    Vector.from:
    for line <- input.split("\n")
    yield line.map(_.asDigit).toVector

    case class Grid(grid: Vector[Vector[Int]]):
    val xRange = grid.head.indices
    val yRange = grid.indices

    enum Dir:
    case N, S, E, W

    def turnRight = this match
    case Dir.N => E
    case Dir.E => S
    case Dir.S => W
    case Dir.W => N

    def turnLeft = this match
    case Dir.N => W
    case Dir.W => S
    case Dir.S => E
    case Dir.E => N

    def grid(using Grid) = summon[Grid].grid
    def xRange(using Grid) = summon[Grid].xRange
    def yRange(using Grid) = summon[Grid].yRange

    case class Point(x: Int, y: Int):
    def inBounds(using Grid) =
    xRange.contains(x) && yRange.contains(y)

    def heatLoss(using Grid) =
    if inBounds then grid(y)(x) else 0

    def move(dir: Dir) = dir match
    case Dir.N => copy(y = y - 1)
    case Dir.S => copy(y = y + 1)
    case Dir.E => copy(x = x + 1)
    case Dir.W => copy(x = x - 1)

    case class State(pos: Point, dir: Dir, streak: Int):
    def straight: State =
    State(pos.move(dir), dir, streak + 1)

    def turnLeft: State =
    val newDir = dir.turnLeft
    State(pos.move(newDir), newDir, 1)

    def turnRight: State =
    val newDir = dir.turnRight
    State(pos.move(newDir), newDir, 1)

    def nextStates(using Grid): List[State] =
    List(straight, turnLeft, turnRight).filter: s =>
    s.pos.inBounds && s.streak <= 3

    def nextStates2(using Grid): List[State] =
    if streak < 4 then List(straight)
    else List(straight, turnLeft, turnRight).filter: s =>
    s.pos.inBounds && s.streak <= 10

    type StateTransform = Grid ?=> State => List[State]

    def solve(input: String, next: StateTransform): Int =
    given Grid = loadGrid(input)
    search(next)

    def search(next: StateTransform)(using Grid): Int =

    val minHeatLoss = Map.empty[State, Int]

    given Ordering[State] = Ordering.by(minHeatLoss)
    val pq = PriorityQueue.empty[State].reverse

    var visiting = State(Point(0, 0), Dir.E, 0)
    minHeatLoss(visiting) = 0

    val end = Point(xRange.max, yRange.max)
    while visiting.pos != end do
    val states = next(visiting).filterNot(minHeatLoss.contains)
    states.foreach: s =>
    minHeatLoss(s) = minHeatLoss(visiting) + s.pos.heatLoss
    pq.enqueue(s)
    visiting = pq.dequeue()

    minHeatLoss(visiting)

    Run it in the browser

    Run Part 1

    Run Part 2

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2023/puzzles/day18/index.html b/2023/puzzles/day18/index.html index ed8330703..6dea1bc68 100644 --- a/2023/puzzles/day18/index.html +++ b/2023/puzzles/day18/index.html @@ -5,7 +5,7 @@ Day 18: Lavaduct Lagoon | Scala Center Advent of Code - + @@ -32,7 +32,7 @@ its direction from the last digit, and its length by converting from the hexadecimal encoding of the remaining digits.

    object Direction:
    def fromInt(i: Char): Direction = i match
    case '0' => Right case '1' => Down case '2' => Left case '3' => Up

    val digPlan = for
    case s"$_ $_ (#$color)" <- input.linesIterator
    dir = Direction.fromInt(color.last)
    len = BigInt(x = color.init, radix = 16)
    yield Trench(dir, len.toInt)

    Final code

    enum Direction:
    case Up, Down, Left, Right
    object Direction:
    def fromChar(c: Char): Direction = c match
    case 'U' => Up case 'D' => Down case 'L' => Left case 'R' => Right
    def fromInt(i: Char): Direction = i match
    case '0' => Right case '1' => Down case '2' => Left case '3' => Up
    import Direction.*

    case class Trench(dir: Direction, length: Int)

    def area(digPlan: Seq[Trench]): Long =
    val (_, area) = digPlan.foldLeft((0, 0), 1L):
    case (((x, y), area), Trench(dir, len)) => dir match
    case Right => ((x + len, y), area + len)
    case Down => ((x, y + len), area + (x + 1) * len.toLong)
    case Left => ((x - len, y), area)
    case Up => ((x, y - len), area - x * len.toLong)
    area

    def part1(input: String): String =
    val digPlan = for
    case s"$dirC $len (#$_)" <- input.linesIterator
    dir = Direction.fromChar(dirC.head)
    yield Trench(dir, len.toInt)

    area(digPlan.toSeq).toString

    def part2(input: String): String =
    val digPlan = for
    case s"$_ $_ (#$color)" <- input.linesIterator
    dir = Direction.fromInt(color.last)
    len = BigInt(x = color.init, radix = 16)
    yield Trench(dir, len.toInt)

    area(digPlan.toSeq).toString

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2023/puzzles/day19/index.html b/2023/puzzles/day19/index.html index 4abf47d1a..80a32ffdc 100644 --- a/2023/puzzles/day19/index.html +++ b/2023/puzzles/day19/index.html @@ -5,14 +5,14 @@ Day 19: Aplenty | Scala Center Advent of Code - +
    Skip to main content

    Day 19: Aplenty

    by @mbovel

    Puzzle description

    https://adventofcode.com/2023/day/19

    Data structures

    We define the following data structures for today's puzzle:

    enum Channel:
    case X, M, A, S

    enum Operator:
    case LessThan, GreaterThan

    enum Result:
    case Reject, Accept

    enum Instruction:
    case IfThenElse(
    channel: Channel,
    operator: Operator,
    value: Int,
    thenBranch: GoTo | Return,
    elseBranch: Instruction
    )
    case Return(result: Result)
    case GoTo(target: String)

    import Instruction.*

    type Workflow = Map[String, Instruction]

    case class Part(x: Int, m: Int, a: Int, s: Int)

    Parsing

    Then, we write the associated parsing methods, using String's split method and regular expression patterns

    object Channel:
    def parse(input: String): Channel =
    input match
    case "x" => Channel.X
    case "m" => Channel.M
    case "a" => Channel.A
    case "s" => Channel.S
    case _ => throw Exception(s"Invalid channel: $input")

    object Operator:
    def parse(input: String): Operator =
    input match
    case "<" => Operator.LessThan
    case ">" => Operator.GreaterThan
    case _ => throw Exception(s"Invalid operator: $input")

    object Result:
    def parse(input: String): Result =
    input match
    case "R" => Result.Reject
    case "A" => Result.Accept
    case _ => throw Exception(s"Invalid result: $input")

    object Instruction:
    private val IfThenElseRegex = """([xmas])([<>])(\d+):(\w+),(.*)""".r
    private val ReturnRegex = """([RA])""".r
    private val GoToRegex = """(\w+)""".r
    def parse(input: String): Instruction =
    input match
    case IfThenElseRegex(channel, operator, value, thenBranch, elseBranch) =>
    Instruction.parse(thenBranch) match
    case thenBranch: (GoTo | Return) =>
    IfThenElse(
    Channel.parse(channel),
    Operator.parse(operator),
    value.toInt,
    thenBranch,
    Instruction.parse(elseBranch)
    )
    case _ => throw Exception(s"Invalid then branch: $thenBranch")
    case ReturnRegex(result) => Return(Result.parse(result))
    case GoToRegex(target) => GoTo(target)
    case _ => throw Exception(s"Invalid instruction: $input")

    object Workflow:
    def parse(input: String): Workflow =
    input.split("\n").map(parseBlock).toMap

    private val BlockRegex = """(\w+)\{(.*?)\}""".r
    private def parseBlock(input: String): (String, Instruction) =
    input match
    case BlockRegex(label, body) =>
    (label, Instruction.parse(body))

    object Part:
    val PartRegex = """\{x=(\d+),m=(\d+),a=(\d+),s=(\d+)\}""".r
    def parse(input: String): Part =
    input match
    case PartRegex(x, m, a, s) => Part(x.toInt, m.toInt, a.toInt, s.toInt)
    case _ => throw Exception(s"Invalid part: $input")

    Part 1 – Evaluation

    These helpers allow us to implement the core logic succinctly:

    def part1(input: String): Int =
    val Array(workflowLines, partLines) = input.split("\n\n")
    val workflow = Workflow.parse(workflowLines.trim())
    val parts = partLines.trim().split("\n").map(Part.parse)

    def eval(part: Part, instruction: Instruction): Result =
    instruction match
    case IfThenElse(channel, operator, value, thenBranch, elseBranch) =>
    val channelValue = channel match
    case Channel.X => part.x
    case Channel.M => part.m
    case Channel.A => part.a
    case Channel.S => part.s
    val result = operator match
    case Operator.LessThan => channelValue < value
    case Operator.GreaterThan => channelValue > value
    if result then eval(part, thenBranch) else eval(part, elseBranch)
    case Return(result) => result
    case GoTo(target) => eval(part, workflow(target))

    parts
    .collect: part =>
    eval(part, workflow("in")) match
    case Result.Reject => 0
    case Result.Accept => part.x + part.m + part.a + part.s
    .sum

    Part 2 – Symbolic execution

    To solve the second part efficiently, we use symbolic execution to count the number of executions of the workflow that lead to an Accept result.

    We represent symbolic values with the AbstractPart structure, where the value associated to each channel is not a number, but a range of possible values:

    case class Range(from: Long, until: Long):
    assert(from < until)
    def count() = until - from

    object Range:
    def safe(from: Long, until: Long): Option[Range] =
    if from < until then Some(Range(from, until)) else None

    case class AbstractPart(x: Range, m: Range, a: Range, s: Range):
    def count() = x.count() * m.count() * a.count() * s.count()

    def withChannel(channel: Channel, newRange: Range) =
    channel match
    case Channel.X => copy(x = newRange)
    case Channel.M => copy(m = newRange)
    case Channel.A => copy(a = newRange)
    case Channel.S => copy(s = newRange)

    def getChannel(channel: Channel) =
    channel match
    case Channel.X => x
    case Channel.M => m
    case Channel.A => a
    case Channel.S => s

    We will start the evaluation with abstract parts that contain all possible values for each channel: four ranges from 1 until 4001.

    When we evaluate an IfThenElse instruction, we split the argument AbstractPart into two parts, one that contains only the values that satisfy the condition, and one that contains only the values that do not satisfy the condition.

    This is achieved with the split method of AbstractPart:

      def split(
    channel: Channel,
    value: Int
    ): (Option[AbstractPart], Option[AbstractPart]) =
    val currentRange = getChannel(channel)
    (
    Range.safe(currentRange.from, value).map(withChannel(channel, _)),
    Range.safe(value, currentRange.until).map(withChannel(channel, _))
    )

    Using these helpers, we can implement the abstract evaluator as follows:

    def part2(input: String): Long = combinations(input, 4001)

    extension [T](part: (T, T)) private inline def swap: (T, T) = (part._2, part._1)

    def combinations(input: String, until: Long): Long =
    val Array(workflowLines, _) = input.split("\n\n")
    val workflow = Workflow.parse(workflowLines.trim())

    def count(part: AbstractPart, instruction: Instruction): Long =
    instruction match
    case IfThenElse(channel, operator, value, thenBranch, elseBranch) =>
    val (trueValues, falseValues) =
    operator match
    case Operator.LessThan => part.split(channel, value)
    case Operator.GreaterThan => part.split(channel, value + 1).swap
    trueValues.map(count(_, thenBranch)).getOrElse(0L)
    + falseValues.map(count(_, elseBranch)).getOrElse(0L)
    case Return(Result.Accept) => part.count()
    case Return(Result.Reject) => 0L
    case GoTo(target) => count(part, workflow(target))

    count(
    AbstractPart(
    Range(1, until),
    Range(1, until),
    Range(1, until),
    Range(1, until)
    ),
    workflow("in")
    )

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2023/puzzles/day20/index.html b/2023/puzzles/day20/index.html index dca3b3e91..4f9c3b3ff 100644 --- a/2023/puzzles/day20/index.html +++ b/2023/puzzles/day20/index.html @@ -5,7 +5,7 @@ Day 20: Pulse Propagation | Scala Center Advent of Code - + @@ -84,7 +84,7 @@ button press count at that point.

    extension (self: Problem2FSM)
    inline def +(state: MachineFSM): Problem2FSM =
    import self.*
    state.queue.headOption match
    case Some(Pulse(src, _, true)) if cycles.get(src).contains(0L) =>
    copy(cycles = cycles + (src -> state.presses))
    case _ => self

    Part 2 Solution

    Part 2 is solved identically to part 1, combining the state machines and iterating until we reach a solution.

    def part2(input: String): Long =
    val machine = parse(input)
    Iterator
    .iterate(MachineFSM(machine))(nextState)
    .scanLeft(Problem2FSM.from(machine))(_ + _)
    .findMap(Problem2FSM.solution)

    Final Code

    The complete, rather lengthy solution follows:

    import scala.annotation.tailrec
    import scala.collection.immutable.Queue

    type ModuleName = String

    // Pulses are the messages of our primary state machine. They are either low
    // (false) or high (true) and travel from a source to a destination module
    final case class Pulse(
    source: ModuleName,
    destination: ModuleName,
    level: Boolean,
    )

    object Pulse:
    final val ButtonPress = Pulse("button", "broadcaster", false)

    // The modules include pass-throughs which simply forward pulses, flip flips
    // which toggle state and emit when they receive a low pulse, and conjunctions
    // which emit a low signal when all inputs are high.

    sealed trait Module:
    def name: ModuleName
    def destinations: Vector[ModuleName]
    // Generate pulses for all the destinations of this module
    def pulses(level: Boolean): Vector[Pulse] =
    destinations.map(Pulse(name, _, level))
    end Module

    final case class PassThrough(
    name: ModuleName,
    destinations: Vector[ModuleName],
    ) extends Module

    final case class FlipFlop(
    name: ModuleName,
    destinations: Vector[ModuleName],
    state: Boolean,
    ) extends Module

    final case class Conjunction(
    name: ModuleName,
    destinations: Vector[ModuleName],
    // The source modules that most-recently sent a high pulse
    state: Set[ModuleName],
    ) extends Module

    // The machine comprises a collection of named modules and a map that gathers
    // which modules serve as sources for each module in the machine.

    final case class Machine(
    modules: Map[ModuleName, Module],
    sources: Map[ModuleName, Set[ModuleName]]
    )

    object Machine:
    val Initial = Machine(Map.empty, Map.empty)

    extension (self: Machine)
    inline def +(module: Module): Machine =
    import self.*
    copy(
    modules = modules.updated(module.name, module),
    sources = module.destinations.foldLeft(sources): (sources, destination) =>
    sources.updatedWith(destination):
    case None => Some(Set(module.name))
    case Some(values) => Some(values + module.name)
    )

    val Initial = Machine(Map.empty, Map.empty)

    // To parse the input we first parse all of the modules and then fold them
    // into a new machine
    def parse(input: String): Machine =
    val modules = input.linesIterator.map:
    case s"%$name -> $targets" =>
    FlipFlop(name, targets.split(", ").toVector, false)
    case s"&$name -> $targets" =>
    Conjunction(name, targets.split(", ").toVector, Set.empty)
    case s"$name -> $targets" =>
    PassThrough(name, targets.split(", ").toVector)
    modules.foldLeft(Machine.Initial)(_ + _)

    // The primary state machine state comprises the machine itself, the number of
    // button presses and a queue of outstanding pulses.

    final case class MachineFSM(
    machine: Machine,
    presses: Long = 0,
    queue: Queue[Pulse] = Queue.empty,
    )

    def nextState(fsm: MachineFSM): MachineFSM =
    import fsm.*

    queue.dequeueOption match
    case None =>
    copy(presses = presses + 1, queue = Queue(Pulse.ButtonPress))

    case Some((Pulse(source, destination, level), tail)) =>
    machine.modules.get(destination) match
    case Some(passThrough: PassThrough) =>
    copy(queue = tail ++ passThrough.pulses(level))

    case Some(flipFlop: FlipFlop) if !level =>
    val flipFlop2 = flipFlop.copy(state = !flipFlop.state)
    copy(
    machine = machine + flipFlop2,
    queue = tail ++ flipFlop2.pulses(flipFlop2.state)
    )

    case Some(conjunction: Conjunction) =>
    val conjunction2 = conjunction.copy(
    state = if level then conjunction.state + source
    else conjunction.state - source
    )
    val active = machine.sources(conjunction2.name) == conjunction2.state
    copy(
    machine = machine + conjunction2,
    queue = tail ++ conjunction2.pulses(!active)
    )

    case _ =>
    copy(queue = tail)
    end nextState

    // An unruly and lawless find-map-get
    extension [A](self: Iterator[A])
    def findMap[B](f: A => Option[B]): B = self.flatMap(f).next()

    // The problem 1 state machine comprises the number of low and high pulses
    // processed, and whether the problem is complete (after 1000 presses). This
    // state machine gets updated by each state of the primary state machine.

    final case class Problem1FSM(
    lows: Long,
    highs: Long,
    complete: Boolean,
    )

    object Problem1FSM:
    final val Initial = Problem1FSM(0, 0, false)

    // The result is the product of lows and highs
    def solution(fsm: Problem1FSM): Option[Long] =
    import fsm.*
    Option.when(complete)(lows * highs)

    // If the head of the pulse queue is a low or high pulse then update the
    // low/high count. If the pulse queue is empty and the button has been pressed
    // 1000 times then complete.

    extension (self: Problem1FSM)
    inline def +(state: MachineFSM): Problem1FSM =
    import self.*
    state.queue.headOption match
    case Some(Pulse(_, _, false)) => copy(lows = lows + 1)
    case Some(Pulse(_, _, true)) => copy(highs = highs + 1)
    case None if state.presses == 1000 => copy(complete = true)
    case None => self

    // Part 1 is solved by first constructing the primary state machine that
    // executes the pulse machinery. Each state of this machine is then fed to a
    // second problem 1 state machine. We then run the combined state machines to
    // completion.

    def part1(input: String): Long =
    val machine = parse(input)
    Iterator
    .iterate(MachineFSM(machine))(nextState)
    .scanLeft(Problem1FSM.Initial)(_ + _)
    .findMap(Problem1FSM.solution)

    // The problem is characterized by a terminal module ("rx") that is fed by
    // several subgraphs so we look to see which are the sources of the terminal
    // module; these are the subgraphs whose cycle lengths we need to count.
    def subgraphs(machine: Machine): Set[ModuleName] =
    val terminal = (machine.sources.keySet -- machine.modules.keySet).head
    machine.sources(machine.sources(terminal).head)

    // The problem 2 state machine is looking for the least common multiple of the
    // cycle lengths of the subgraphs that feed into the output "rx" module. When it
    // observes a high pulse from the final module of one these subgraphs, it
    // records the number of button presses to reach this state.

    final case class Problem2FSM(
    cycles: Map[ModuleName, Long],
    )

    object Problem2FSM:

    def from(machine: Machine): Problem2FSM =
    Problem2FSM(subgraphs(machine).map(_ -> 0L).toMap)

    private def lcm(list: Iterable[Long]): Long =
    list.foldLeft(1L)((a, b) => b * a / gcd(a, b))

    @tailrec
    private def gcd(x: Long, y: Long): Long =
    if y == 0 then x else gcd(y, x % y)

    def solution(fsm: Problem2FSM): Option[Long] =
    import fsm.cycles
    Option.when(cycles.values.forall(_ > 0))(lcm(cycles.values))

    extension (self: Problem2FSM)
    inline def +(state: MachineFSM): Problem2FSM =
    import self.*
    state.queue.headOption match
    case Some(Pulse(src, _, true)) if cycles.get(src).contains(0L) =>
    copy(cycles = cycles + (src -> state.presses))
    case _ => self

    // Part 2 is solved by first constructing the primary state machine that
    // executes the pulse machinery. Each state of this machine is then fed to a
    // second problem 2 state machine. We then run the combined state machines to
    // completion.

    def part2(input: String): Long =
    val machine = parse(input)
    Iterator
    .iterate(MachineFSM(machine))(nextState)
    .scanLeft(Problem2FSM.from(machine))(_ + _)
    .findMap(Problem2FSM.solution)

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2023/puzzles/day21/index.html b/2023/puzzles/day21/index.html index 6fcc2bff4..33f92e72d 100644 --- a/2023/puzzles/day21/index.html +++ b/2023/puzzles/day21/index.html @@ -5,14 +5,14 @@ Day 21: Step Counter | Scala Center Advent of Code - +
    Skip to main content
    - + \ No newline at end of file diff --git a/2023/puzzles/day22/index.html b/2023/puzzles/day22/index.html index a31ac9f9e..18d4304df 100644 --- a/2023/puzzles/day22/index.html +++ b/2023/puzzles/day22/index.html @@ -5,7 +5,7 @@ Day 22: Sand Slabs | Scala Center Advent of Code - + @@ -34,7 +34,7 @@ a Set underneath. By converting it to a list, we ensure that each count is preserved independently. Without this conversion, if multiple bricks have the same falling chain count, some counts may be lost.

    By combining these individual chain counts and summing them up, we arrive at the answer for Part 2:

    def part2(input: String): Int = {
    val bricks = parse(input)
    val brickToSupportingBricks = dropBricks(bricks)
    val fallingChainCounts = brickToSupportingBricks.keys.toList.map(
    countFallingChain(brickToSupportingBricks)
    )
    fallingChainCounts.sum
    }

    Final code

    case class Coordinate(x: Int, y: Int, z: Int)

    case class Brick(start: Coordinate, end: Coordinate) {

    lazy val moveDown: Brick =
    copy(
    start = start.copy(z = start.z - 1),
    end = end.copy(z = end.z - 1)
    )

    def collidesWith(other: Brick): Boolean =
    axisOverlaps(other)(_.x) &&
    axisOverlaps(other)(_.y) &&
    axisOverlaps(other)(_.z)

    private def axisOverlaps(other: Brick)(axis: Coordinate => Int) = {
    val min = axis(start) min axis(end)
    val max = axis(start) max axis(end)
    val otherMin = axis(other.start) min axis(other.end)
    val otherMax = axis(other.start) max axis(other.end)
    max >= otherMin && otherMax >= min
    }
    }

    def parse(input: String): Seq[Brick] =
    for s"$x1,$y1,$z1~$x2,$y2,$z2" <- input.split('\n')
    yield
    val start = Coordinate(x1.toInt, y1.toInt, z1.toInt)
    val end = Coordinate(x2.toInt, y2.toInt, z2.toInt)
    Brick(start, end)

    import scala.collection.mutable

    def dropBricks(bricks: Seq[Brick]): Map[Brick, Set[Brick]] = {
    val bricksByZAsc = bricks.sortBy(brick => (brick.start.z) min (brick.end.z))
    val remainingBricks = mutable.Stack.from(bricksByZAsc)
    val droppedBricks = mutable.Map[Brick, Set[Brick]]()

    while (remainingBricks.nonEmpty) {
    val brick = remainingBricks.pop()
    val brickMovedDown = brick.moveDown
    val collidingBricks =
    droppedBricks.keys.filter(brickMovedDown.collidesWith).toSet
    if (collidesWithGround(brickMovedDown) || collidingBricks.nonEmpty)
    droppedBricks.put(brick, collidingBricks)
    else
    remainingBricks.push(brickMovedDown)
    }

    droppedBricks.toMap
    }

    def collidesWithGround(brick: Brick): Boolean =
    brick.start.z == 0 || brick.end.z == 0

    def getDisintegrableBricks(brickToSupportingBricks: Map[Brick, Set[Brick]]): Set[Brick] = {
    val nonDisintegrableBricks = brickToSupportingBricks.values.collect {
    case supporting if supporting.sizeIs == 1 =>
    supporting.head // the only brick that holds the brick above
    }.toSet
    brickToSupportingBricks.keySet diff nonDisintegrableBricks
    }

    def part1(input: String): Int = {
    val bricks = parse(input)
    val brickToSupportingBricks = dropBricks(bricks)
    val disintegrableBricks = getDisintegrableBricks(brickToSupportingBricks)
    disintegrableBricks.size
    }

    def countFallingChain(brickToSupportingBricks: Map[Brick, Set[Brick]])(brick: Brick): Int = {
    val disintegratedBricks = mutable.Set[Brick](brick)
    var remainingBricks = brickToSupportingBricks.removed(brick)
    var isChainReactionFinished = false

    while (!isChainReactionFinished) {
    val (newDisintegratedBricks, newRemainingBricks) = remainingBricks
    .partition { (_, supportingBricks) =>
    supportingBricks.nonEmpty && supportingBricks.subsetOf(
    disintegratedBricks
    )
    }
    if (newDisintegratedBricks.isEmpty)
    isChainReactionFinished = true
    else
    disintegratedBricks.addAll(newDisintegratedBricks.keySet)
    remainingBricks = newRemainingBricks
    }

    disintegratedBricks.size - 1 // don't include the initial brick
    }

    def part2(input: String): Int = {
    val bricks = parse(input)
    val brickToSupportingBricks = dropBricks(bricks)
    val fallingChainCounts = brickToSupportingBricks.keys.toList.map(
    countFallingChain(brickToSupportingBricks)
    )
    fallingChainCounts.sum
    }

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2023/puzzles/day23/index.html b/2023/puzzles/day23/index.html index 4b05b0d15..996c2a217 100644 --- a/2023/puzzles/day23/index.html +++ b/2023/puzzles/day23/index.html @@ -5,7 +5,7 @@ Day 23: A Long Walk | Scala Center Advent of Code - + @@ -13,7 +13,7 @@
    Skip to main content

    Day 23: A Long Walk

    by @stewSquared

    Puzzle description

    https://adventofcode.com/2023/day/23

    Solution

    Overview and Observations

    The general problem of finding the longest path through a grid or a graph is NP-hard, so we won't be using any fancy algorithms or heuristics today; we'll use a depth-first backtracking search. For part 2, we'll need some optimizations (graph compression and bitmasking) that reduce the size of the search space and visited set so the algorithm can run in around 2 seconds.

    The general approach to finding the longest path via DFS is to maintain a set of visited positions alongside the current position. The next position can be any adjacent position that isn't in the visited set. We then recursively search from one of those adjacent positions until we find the end, note the path length, then try the other adjacent positions, keeping the longest path length we find.

    For both problems, it is worth noticing that the vast majority of path positions in the maze are only connected to two other paths, so when entering from one path, there is only one path from which we can exit. Some paths are connected to three or four other paths. These paths, we'll call junctions.

    Each junction might have two or three adjacent paths we can enter. When we exit a junction, we will inevitably reach another junction (or the end of the maze). Because of this, every path through the maze is fully determined by the sequence of junctions it enters. This allows us two optimizations:

    • We can compress the grid into an adjacency graph of vertices (the junctions) with weighted edges (the distance of the path between junctions) to other vertices. This allows us to have a distinctly smaller visited set, as there are only ~35 junctions in the puzzle input. This also avoids re-computing the distance between two junctions as we might in a cell-by-cell search of the grid. On my machine, this drops the run time for part 2 from 1 minute to ~10 seconds (90%).

    • For each iteration of the search through this graph, we check all adjacent junctions against the visited set. When using a hash set, this will result in computing hashes of position coordinates tens of millions of times. We can avoid this by giving each junction an index and using a BitSet of these indices as our visited set. Checking for membership in a BitSet only requires a bitshift and a bitwise AND mask. On my machine, this drops the run time from ~7 seconds to ~2 seconds (70%).

    For part 1, neither of these optimizations are necessary. To understand why, notice that every junction is surrounded by slopes. When a junction is surrounded by four slopes, as most of them are, two are incoming and two are outgoing. For part 1, these are arranged in such a way that the adjacency graph becomes a directed acyclic graph, with a greatly reduced search space. One way to notice this early on is to generate a visualization via GraphViz, such as the following:

    G00110->1159331->3138221->280443->472663->63342->4170552->531011114->11232994->91165->11184775->71126->938886->844131311->1374141411->147210109->10209->1418812127->122227->13668->103815158->15440181812->18144202012->2052013->18140171713->17202161610->16120191910->1922215->19184222215->2247214->1619614->17152232316->2394212116->2119819->226019->234018->2060242418->24146282820->2828017->2110217->2456252522->25124262623->2619023->25112272721->2716221->268224->2825024->27104292928->2958313127->3113227->29156303026->309826->3112825->30336333330->33188323231->328431->336229->32392343432->349233->34158353534->3549

    Framework

    First we define a Point case class for representing coordinates, and a Dir enum for representing direction. Direction will be used when "walking" on a path through the maze to calculate whether a slope blocks us and to prevent us from searching adjacent points that are backwards. Similar definitions show up in solutions to other Advent of Code problems:

    case class Point(x: Int, y: Int):
    def dist(p: Point) = math.abs(x - p.x) + math.abs(y - p.y)
    def adjacent = List(copy(x = x + 1), copy(x = x - 1), copy(y = y + 1), copy(y = y - 1))

    def move(dir: Dir) = dir match
    case Dir.N => copy(y = y - 1)
    case Dir.S => copy(y = y + 1)
    case Dir.E => copy(x = x + 1)
    case Dir.W => copy(x = x - 1)
    enum Dir:
    case N, S, E, W

    def turnRight = this match
    case Dir.N => E
    case Dir.E => S
    case Dir.S => W
    case Dir.W => N

    def turnLeft = this match
    case Dir.N => W
    case Dir.W => S
    case Dir.S => E
    case Dir.E => N

    Next we create a Maze class that will give us basic information about the maze from the raw data:

    case class Maze(grid: Vector[Vector[Char]]):

    def apply(p: Point): Char = grid(p.y)(p.x)

    val xRange: Range = grid.head.indices
    val yRange: Range = grid.indices

    def points: Iterator[Point] = for
    y <- yRange.iterator
    x <- xRange.iterator
    yield Point(x, y)

    So far we just have helper methods. The next few definitions are the things we'll really want to know about the maze in order to construct our solutions:

      val walkable: Set[Point] = points.filter(p => grid(p.y)(p.x) != '#').toSet
    val start: Point = walkable.minBy(_.y)
    val end: Point = walkable.maxBy(_.y)

    val junctions: Set[Point] = walkable.filter: p =>
    Dir.values.map(p.move).count(walkable) > 2
    .toSet + start + end

    Here we can populate which points are slopes by looking up a point with this.apply(p), shortened to this(p).

      val slopes: Map[Point, Dir] = Map.from:
    points.collect:
    case p if this(p) == '^' => p -> Dir.N
    case p if this(p) == 'v' => p -> Dir.S
    case p if this(p) == '>' => p -> Dir.E
    case p if this(p) == '<' => p -> Dir.W
    end Maze

    walkable gives us the set of points that are not walls, ie., they are paths or slopes.

    junctions gives us the junction points mentioned in the overview, ie., paths that have multiple entrances or exits. Notice that start and end are part of the set here. While these are not true junctions, we do want them to appear in our adjacency graph.

    slopes gives us the direction of each slope. For Part 1, these are the directions one must be travelling in order to progress past a slope position.

    Finding Connected Junctions

    Next, we need an algorithm for finding junctions that are connected to a given junction, while tracking the distance travelled to reach that junction. This is the heart of our solution, and is necessary for both parts 1 and 2:

    def connectedJunctions(pos: Point)(using maze: Maze): List[(Point, Int)] = List.from:
    assert(maze.junctions.contains(pos))

    This walk helper method attempts to move in a given direction from a given position, accounting for walls and slopes in the maze. This alternatively could have been defined as a method on Point itself.

      def walk(pos: Point, dir: Dir): Option[Point] =
    val p = pos.move(dir)
    Option.when(maze.walkable(p) && maze.slopes.get(p).forall(_ == dir))(p)

    This search helper method walks down a path from a junction while tracking the current direction and distance. adjacentSearch attempts to walk recursively in directions that don't go backwards. A LazyList is used here to prevent stack overflows. If there is only one adjacent path to walk too, we continue searching that path recursively until we reach a junction, otherwise, we have reached a dead end; None represents the fact that no new junctions are reachable down this path.

      def search(pos: Point, facing: Dir, dist: Int): Option[(Point, Int)] =
    if maze.junctions.contains(pos) then
    Some(pos, dist)
    else
    val adjacentSearch = for
    nextFacing <- LazyList(facing, facing.turnRight, facing.turnLeft)
    nextPos <- walk(pos, nextFacing)
    yield search(nextPos, nextFacing, dist + 1)

    if adjacentSearch.size == 1 then adjacentSearch.head else None

    Finally, we begin the search in each direction from our current junction, returning all the connected junctions found.

      for
    d <- Dir.values
    p <- walk(pos, d)
    junction <- search(p, d, 1)
    yield junction
    end connectedJunctions

    Part 1

    connectedJunctions is sufficient to solve Part 1 quickly:

    def part1(input: String): Int =
    given Maze = Maze(parseInput(input))
    longestDownhillHike

    def parseInput(fileContents: String): Vector[Vector[Char]] =
    Vector.from:
    fileContents.split("\n").map(_.toVector)

    def longestDownhillHike(using maze: Maze): Int =
    def search(pos: Point, dist: Int): Int =
    if pos == maze.end then
    dist
    else
    connectedJunctions(pos).foldLeft(0):
    case (max, (n, d)) => max.max(search(n, dist + d))

    search(maze.start, 0)
    end longestDownhillHike

    This uses a recursive helper method named search. Beginning with start, we recursively search for the longest path starting at each of the connected junctions.

    Part 2

    For part 2, we'll implement the optimization mentioned in the overview, namely, bitmasking and graph compression. Graph compression is partially implemented in connectedJunctions, but we'll want to avoid recomputation by storing the full graph as a map from a junction, to a list of connected junctions and the distances to each of those junctions.

    def part2(input: String): Int =
    given Maze = Maze(parseInput(input))
    longestHike

    def longestHike(using maze: Maze): Int =
    type Index = Int

    We begin by assigning indices to each of the junctions, by sorting them (in any way, as long as the ordering is well-defined) and zipping with an index:

      val indexOf: Map[Point, Index] =
    maze.junctions.toList.sortBy(_.dist(maze.start)).zipWithIndex.toMap

    Next, we define an adjacency graph. Since connectedJunctions takes slopes into account, and we no longer care about slopes for part 2, we add both the forward and reverse directions into our Map. Note how we translate the Point locations used by connectedJunctions into indices using indexOf, defined above:

      val adjacent: Map[Index, List[(Index, Int)]] =
    maze.junctions.toList
    .flatMap: p1 =>
    connectedJunctions(p1).flatMap: (p2, d) =>
    val forward = indexOf(p1) -> (indexOf(p2), d)
    val reverse = indexOf(p2) -> (indexOf(p1), d)
    List(forward, reverse)
    .groupMap(_(0))(_(1))

    Finally, we perform a depth-first search that is very similar to what we used in Part 1. The main differences are that we now use indices of junctions rather than Points representing current position, and we now check adjacent junctions against a BitSet of visited points, which we now track as we search recursively.

      def search(junction: Index, visited: BitSet, totalDist: Int): Int =
    if junction == indexOf(maze.end) then
    totalDist
    else
    adjacent(junction).foldLeft(0):
    case (longest, (nextJunct, dist)) =>
    if visited(nextJunct) then longest else
    longest.max(search(nextJunct, visited + nextJunct, totalDist + dist))

    search(indexOf(maze.start), BitSet.empty, 0)
    end longestHike

    Final Code

    import collection.immutable.BitSet

    def part1(input: String): Int =
    given Maze = Maze(parseInput(input))
    longestDownhillHike

    def part2(input: String): Int =
    given Maze = Maze(parseInput(input))
    longestHike

    def parseInput(fileContents: String): Vector[Vector[Char]] =
    Vector.from:
    fileContents.split("\n").map(_.toVector)

    enum Dir:
    case N, S, E, W

    def turnRight = this match
    case Dir.N => E
    case Dir.E => S
    case Dir.S => W
    case Dir.W => N

    def turnLeft = this match
    case Dir.N => W
    case Dir.W => S
    case Dir.S => E
    case Dir.E => N

    case class Point(x: Int, y: Int):
    def dist(p: Point) = math.abs(x - p.x) + math.abs(y - p.y)
    def adjacent = List(copy(x = x + 1), copy(x = x - 1), copy(y = y + 1), copy(y = y - 1))

    def move(dir: Dir) = dir match
    case Dir.N => copy(y = y - 1)
    case Dir.S => copy(y = y + 1)
    case Dir.E => copy(x = x + 1)
    case Dir.W => copy(x = x - 1)

    case class Maze(grid: Vector[Vector[Char]]):

    def apply(p: Point): Char = grid(p.y)(p.x)

    val xRange: Range = grid.head.indices
    val yRange: Range = grid.indices

    def points: Iterator[Point] = for
    y <- yRange.iterator
    x <- xRange.iterator
    yield Point(x, y)

    val walkable: Set[Point] = points.filter(p => grid(p.y)(p.x) != '#').toSet
    val start: Point = walkable.minBy(_.y)
    val end: Point = walkable.maxBy(_.y)

    val junctions: Set[Point] = walkable.filter: p =>
    Dir.values.map(p.move).count(walkable) > 2
    .toSet + start + end

    val slopes: Map[Point, Dir] = Map.from:
    points.collect:
    case p if this(p) == '^' => p -> Dir.N
    case p if this(p) == 'v' => p -> Dir.S
    case p if this(p) == '>' => p -> Dir.E
    case p if this(p) == '<' => p -> Dir.W
    end Maze

    def connectedJunctions(pos: Point)(using maze: Maze): List[(Point, Int)] = List.from:
    def walk(pos: Point, dir: Dir): Option[Point] =
    val p = pos.move(dir)
    Option.when(maze.walkable(p) && maze.slopes.get(p).forall(_ == dir))(p)

    def search(pos: Point, facing: Dir, dist: Int): Option[(Point, Int)] =
    if maze.junctions.contains(pos) then
    Some(pos, dist)
    else
    val adjacentSearch = for
    nextFacing <- LazyList(facing, facing.turnRight, facing.turnLeft)
    nextPos <- walk(pos, nextFacing)
    yield search(nextPos, nextFacing, dist + 1)

    if adjacentSearch.size == 1 then adjacentSearch.head else None

    for
    d <- Dir.values
    p <- walk(pos, d)
    junction <- search(p, d, 1)
    yield junction
    end connectedJunctions

    def longestDownhillHike(using maze: Maze): Int =
    def search(pos: Point, dist: Int): Int =
    if pos == maze.end then
    dist
    else
    connectedJunctions(pos).foldLeft(0):
    case (max, (n, d)) => max.max(search(n, dist + d))

    search(maze.start, 0)
    end longestDownhillHike

    def longestHike(using maze: Maze): Int =
    type Index = Int

    val indexOf: Map[Point, Index] =
    maze.junctions.toList.sortBy(_.dist(maze.start)).zipWithIndex.toMap

    val adjacent: Map[Index, List[(Index, Int)]] =
    maze.junctions.toList
    .flatMap: p1 =>
    connectedJunctions(p1).flatMap: (p2, d) =>
    val forward = indexOf(p1) -> (indexOf(p2), d)
    val reverse = indexOf(p2) -> (indexOf(p1), d)
    List(forward, reverse)
    .groupMap(_(0))(_(1))

    def search(junction: Index, visited: BitSet, totalDist: Int): Int =
    if junction == indexOf(maze.end) then
    totalDist
    else
    adjacent(junction).foldLeft(0):
    case (longest, (nextJunct, dist)) =>
    if visited(nextJunct) then longest else
    longest.max(search(nextJunct, visited + nextJunct, totalDist + dist))

    search(indexOf(maze.start), BitSet.empty, 0)
    end longestHike

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2023/puzzles/day24/index.html b/2023/puzzles/day24/index.html index 95f911988..e703c3462 100644 --- a/2023/puzzles/day24/index.html +++ b/2023/puzzles/day24/index.html @@ -5,7 +5,7 @@ Day 24: Never Tell Me The Odds | Scala Center Advent of Code - + @@ -81,7 +81,7 @@ since the x velocity is already known, so we only need to test z candidates, but this is less effort.

    First add a method xzProjection method to Hail to get a 2D projection:

    // Inside class Hail:
    def xzProjection: Hail2D = Hail2D(x, z, vx, vz)

    Next, add a helper method to find a value in an iterator:

    // An unruly and lawless find-map-get
    extension [A](self: Iterator[A])
    def findMap[B](f: A => Option[B]): B = self.flatMap(f).next()

    Finally solve part 2

    def part2(input: String): Long =
    val hails = parseAll(input)

    val hailsXY = hails.map(_.xyProjection)
    val (x, y) = Iterator
    .iterate(Spiral.Start)(_.next)
    .findMap: spiral =>
    findRockOrigin(hailsXY, spiral.x, spiral.y)

    val hailsXZ = hails.map(_.xzProjection)
    val (_, z) = Iterator
    .iterate(Spiral.Start)(_.next)
    .findMap: spiral =>
    findRockOrigin(hailsXZ, spiral.x, spiral.y)

    x + y + z
    end part2

    Final Code

    The complete solution follows:

    final case class Hail(x: Long, y: Long, z: Long, vx: Long, vy: Long, vz: Long):
    def xyProjection: Hail2D = Hail2D(x, y, vx, vy)
    def xzProjection: Hail2D = Hail2D(x, z, vx, vz)

    def parseAll(input: String): Vector[Hail] =
    input.linesIterator.toVector.map:
    case s"$x, $y, $z @ $dx, $dy, $dz" =>
    Hail(x.trim.toLong, y.trim.toLong, z.trim.toLong,
    dx.trim.toLong, dy.trim.toLong, dz.trim.toLong)

    final case class Hail2D(x: Long, y: Long, vx: Long, vy: Long):
    private val a: BigDecimal = BigDecimal(vy)
    private val b: BigDecimal = BigDecimal(-vx)
    private val c: BigDecimal = BigDecimal(vx * y - vy * x)

    def deltaV(dvx: Long, dvy: Long): Hail2D = copy(vx = vx - dvx, vy = vy - dvy)

    // If the paths of these hailstones intersect, return the intersection
    def intersect(hail: Hail2D): Option[(BigDecimal, BigDecimal)] =
    val denominator = a * hail.b - hail.a * b
    Option.when(denominator != 0):
    ((b * hail.c - hail.b * c) / denominator,
    (c * hail.a - hail.c * a) / denominator)

    // Return the time at which this hail will intersect the given point
    def timeTo(posX: BigDecimal, posY: BigDecimal): BigDecimal =
    if vx == 0 then (posY - y) / vy else (posX - x) / vx
    end Hail2D

    extension [A](self: Vector[A])
    // all non-self element pairs
    def allPairs: Vector[(A, A)] = self.tails.toVector.tail.flatMap(self.zip)

    extension [A](self: Iterator[A])
    // An unruly and lawless find-map-get
    def findMap[B](f: A => Option[B]): B = self.flatMap(f).next()

    def intersections(
    hails: Vector[Hail2D],
    min: Long,
    max: Long
    ): Vector[(Hail2D, Hail2D)] =
    for
    (hail0, hail1) <- hails.allPairs
    (x, y) <- hail0.intersect(hail1)
    if x >= min && x <= max && y >= min && y <= max &&
    hail0.timeTo(x, y) >= 0 && hail1.timeTo(x, y) >= 0
    yield (hail0, hail1)
    end intersections

    def part1(input: String): Long =
    val hails = Hail.parseAll(input)
    val hailsXY = hails.map(_.xyProjection)
    intersections(hailsXY, 200000000000000L, 400000000000000L).size
    end part1

    def findRockOrigin(
    hails: Vector[Hail2D],
    vx: Long,
    vy: Long
    ): Option[(Long, Long)] =
    val hail0 +: hail1 +: hail2 +: _ = hails.map(_.deltaV(vx, vy)): @unchecked
    for
    (x0, y0) <- hail0.intersect(hail1)
    (x1, y1) <- hail0.intersect(hail2)
    if x0 == x1 && y0 == y1
    time = hail0.timeTo(x0, y0)
    yield (hail0.x + hail0.vx * time.longValue,
    hail0.y + hail0.vy * time.longValue)
    end findRockOrigin

    final case class Spiral(
    x: Long, y: Long,
    dx: Long, dy: Long,
    count: Long, limit: Long,
    ):
    def next: Spiral =
    if count > 0 then
    copy(x = x + dx, y = y + dy, count = count - 1)
    else if dy == 0 then
    copy(x = x + dx, y = y + dy, dy = dx, dx = -dy, count = limit)
    else
    copy(x = x + dx, y = y + dy, dy = dx, dx = -dy,
    count = limit + 1, limit = limit + 1)
    end next
    end Spiral

    object Spiral:
    final val Start = Spiral(0, 0, 1, 0, 0, 0)

    def part2(input: String): Long =
    val hails = Hail.parseAll(input)

    val hailsXY = hails.map(_.xyProjection)
    val (x, y) = Iterator
    .iterate(Spiral.Start)(_.next)
    .findMap: spiral =>
    findRockOrigin(hailsXY, spiral.x, spiral.y)

    val hailsXZ = hails.map(_.xzProjection)
    val (_, z) = Iterator
    .iterate(Spiral.Start)(_.next)
    .findMap: spiral =>
    findRockOrigin(hailsXZ, spiral.x, spiral.y)

    x + y + z
    end part2

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2023/puzzles/day25/index.html b/2023/puzzles/day25/index.html index f5e684758..56c533273 100644 --- a/2023/puzzles/day25/index.html +++ b/2023/puzzles/day25/index.html @@ -5,7 +5,7 @@ Day 25: Snowverload | Scala Center Advent of Code - + @@ -34,7 +34,7 @@ We will have to do the following processing steps to build a suitable graph representation:

    Here is the code:

    def readGraph(alist: Map[String, Set[String]]): Graph =
    val all = alist.flatMap((k, vs) => vs + k).toSet

    val (_, lookup) =
    // perfect hashing
    val initial = (0, Map.empty[String, Id])
    all.foldLeft(initial): (acc, s) =>
    val (id, seen) = acc
    (id + 1, seen + (s -> id))

    def asEdges(k: String, v: String) =
    val t = (lookup(k), lookup(v))
    t :: t.swap :: Nil

    val v = lookup.values.to(BitSet)
    val nodes = v.unsorted.map(id => id -> BitSet(id)).toMap
    val edges =
    for
    (k, vs) <- alist.toSet
    v <- vs
    e <- asEdges(k, v) // (k -> v) + (v -> k)
    yield
    e

    val w = edges
    .groupBy((v, _) => v)
    .view
    .mapValues: m =>
    m
    .groupBy((_, v) => v)
    .view
    .mapValues(_ => 1)
    .toMap
    .toMap
    Graph(v, nodes, w)

    The Solution

    Putting everything together, we can now solve the problem!

    def part1(input: String): Int =
    val alist = parse(input) // 1.
    val g = readGraph(alist) // 2.
    val (graph, cut) = minimumCut(g) // 3.
    val (out, in) = graph.partition(cut) // 4.
    in.size * out.size // 5.
    1. Parse the input into an adjacency list (note. the edges are directed)
    2. Convert the adjacency list to the Graph structure.
    3. Call the minimumCut function on the graph, storing the minimum cut, and the state of the graph when the cut was made.
    4. use the cut on the graph to get the partition of vertices.
    5. multiply the sizes of the partitions to get the final answer.

    Final Code

    import scala.collection.immutable.BitSet
    import scala.collection.immutable.TreeSet

    def part1(input: String): Int =
    val alist = parse(input)
    val g = readGraph(alist)
    val (graph, cut) = minimumCut(g)
    val (out, in) = graph.partition(cut)
    in.size * out.size

    type Id = Int
    type Vertices = BitSet
    type Weight = Map[Id, Map[Id, Int]]

    def parse(input: String): Map[String, Set[String]] =
    input
    .linesIterator
    .map:
    case s"$key: $values" => key -> values.split(" ").toSet
    .toMap

    def readGraph(alist: Map[String, Set[String]]): Graph =
    val all = alist.flatMap((k, vs) => vs + k).toSet

    val (_, lookup) =
    // perfect hashing
    val initial = (0, Map.empty[String, Id])
    all.foldLeft(initial): (acc, s) =>
    val (id, seen) = acc
    (id + 1, seen + (s -> id))

    def asEdges(k: String, v: String) =
    val t = (lookup(k), lookup(v))
    t :: t.swap :: Nil

    val v = lookup.values.to(BitSet)
    val nodes = v.unsorted.map(id => id -> BitSet(id)).toMap
    val edges =
    for
    (k, vs) <- alist.toSet
    v <- vs
    e <- asEdges(k, v)
    yield
    e

    val w = edges
    .groupBy((v, _) => v)
    .view
    .mapValues: m =>
    m
    .groupBy((_, v) => v)
    .view
    .mapValues(_ => 1)
    .toMap
    .toMap
    Graph(v, nodes, w)

    class MostConnected(
    totalWeights: Map[Id, Int],
    queue: TreeSet[MostConnected.Entry]
    ):

    def pop =
    val id = queue.head.id
    id -> MostConnected(totalWeights - id, queue.tail)

    def expand(z: Id, explore: Vertices, w: Weight) =
    val connectedEdges =
    w(z).view.filterKeys(explore)
    var totalWeights0 = totalWeights
    var queue0 = queue
    for (id, w) <- connectedEdges do
    val w1 = totalWeights0.getOrElse(id, 0) + w
    totalWeights0 += id -> w1
    queue0 += MostConnected.Entry(id, w1)
    MostConnected(totalWeights0, queue0)
    end expand

    end MostConnected

    object MostConnected:
    def empty = MostConnected(Map.empty, TreeSet.empty)
    given Ordering[Entry] = (e1, e2) =>
    val first = e2.weight.compareTo(e1.weight)
    if first == 0 then e2.id.compareTo(e1.id) else first
    class Entry(val id: Id, val weight: Int):
    override def hashCode: Int = id
    override def equals(that: Any): Boolean = that match
    case that: Entry => id == that.id
    case _ => false

    case class Graph(v: Vertices, nodes: Map[Id, Vertices], w: Weight):
    def cutOfThePhase(t: Id) = Graph.Cut(t = t, edges = w(t))

    def partition(cut: Graph.Cut): (Vertices, Vertices) =
    (nodes(cut.t), (v - cut.t).flatMap(nodes))

    def shrink(s: Id, t: Id): Graph =
    def fetch(x: Id) =
    w(x).view.filterKeys(y => y != s && y != t)

    val prunedW = (w - t).view.mapValues(_ - t).toMap

    val fromS = fetch(s).toMap
    val fromT = fetch(t).map: (y, w0) =>
    y -> (fromS.getOrElse(y, 0) + w0)
    val mergedWeights = fromS ++ fromT

    val reverseMerged = mergedWeights.view.map: (y, w0) =>
    y -> (prunedW(y) + (s -> w0))

    val v1 = v - t // 5.
    val w1 = prunedW + (s -> mergedWeights) ++ reverseMerged
    val nodes1 = nodes - t + (s -> (nodes(s) ++ nodes(t)))
    Graph(v1, nodes1, w1)
    end shrink

    object Graph:
    def emptyCut = Cut(t = -1, edges = Map.empty)

    case class Cut(t: Id, edges: Map[Id, Int]):
    lazy val weight: Int = edges.values.sum

    def minimumCutPhase(g: Graph) =
    val a = g.v.head
    var A = a :: Nil
    var explore = g.v - a
    var mostConnected =
    MostConnected.empty.expand(a, explore, g.w)
    while explore.nonEmpty do
    val (z, rest) = mostConnected.pop
    A ::= z
    explore -= z
    mostConnected = rest.expand(z, explore, g.w)
    val t :: s :: _ = A: @unchecked
    (g.shrink(s, t), g.cutOfThePhase(t))

    /** See Stoer-Wagner min cut algorithm
    * https://dl.acm.org/doi/pdf/10.1145/263867.263872
    */
    def minimumCut(g: Graph) =
    var g0 = g
    var min = (g, Graph.emptyCut)
    while g0.v.size > 1 do
    val (g1, cutOfThePhase) = minimumCutPhase(g0)
    if cutOfThePhase.weight < min(1).weight
    || min(1).weight == 0 // initial case
    then
    min = (g0, cutOfThePhase)
    g0 = g1
    min

    Run it in the browser

    Part 1

    Beware that Safari is not able to run this solution efficiently (Chrome and Firefox are ok)

    There is no part 2 for this day!

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2024/index.html b/2024/index.html index 2a932f515..bff52c20c 100644 --- a/2024/index.html +++ b/2024/index.html @@ -5,13 +5,13 @@ Scala Center Advent of Code | Scala Center Advent of Code - +
    Skip to main content
    Credit to https://github.com/OlegIlyenko/scala-icon

    Learn Scala 3

    A simpler, safer and more concise version of Scala, the famous object-oriented and functional programming language.

    Solve Advent of Code puzzles

    Challenge your programming skills by solving Advent of Code puzzles.

    Share with the community

    Get or give support to the community. Share your solutions with the community.

    - + \ No newline at end of file diff --git a/2024/puzzles/day0/index.html b/2024/puzzles/day0/index.html index 49f0572fa..665e7f8f2 100644 --- a/2024/puzzles/day0/index.html +++ b/2024/puzzles/day0/index.html @@ -5,13 +5,13 @@ Redirecting... - +
    Skip to main content
    - + \ No newline at end of file diff --git a/2024/puzzles/day01/index.html b/2024/puzzles/day01/index.html index 5d6c91690..846afa81b 100644 --- a/2024/puzzles/day01/index.html +++ b/2024/puzzles/day01/index.html @@ -5,7 +5,7 @@ Day 1: Historian Hysteria | Scala Center Advent of Code - + @@ -20,7 +20,7 @@ then multiply that count by the number itself. Finally we sum the similarity scores of all the left numbers:

    def part2(input: String): Long =
    val (lefts, rights) = parse(input)
    lefts
    .map(left => rights.count(_ == left) * left) // similarity scores
    .sum
    end part2

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2024/puzzles/day02/index.html b/2024/puzzles/day02/index.html index 59c867aae..d99c938c7 100644 --- a/2024/puzzles/day02/index.html +++ b/2024/puzzles/day02/index.html @@ -5,7 +5,7 @@ Day 2: Red-Nosed Reports | Scala Center Advent of Code - + @@ -20,7 +20,7 @@ but our puzzle inputs are fairly short (there are at most 8 levels in each Report), so it's a simple approach that reuses the isSafe method from Part 1.

    Part 2 solver now counts the dampened safe reports:

    def part2(input: String): Int = parse(input).count(_.isDampenedSafe)

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2024/puzzles/day03/index.html b/2024/puzzles/day03/index.html index 5cf55757e..0818f810c 100644 --- a/2024/puzzles/day03/index.html +++ b/2024/puzzles/day03/index.html @@ -5,14 +5,14 @@ Day 3: Mull It Over | Scala Center Advent of Code - +
    Skip to main content

    Day 3: Mull It Over

    by @makingthematrix

    Puzzle description

    https://adventofcode.com/2024/day/3

    Solution Summary

    1. Part 1:
      • Write a regex to find a string that looks like "mul(a,b)" where a and b are integers.
      • Run the regex over the input string and find all matches.
      • For each match extract a and b and multiply them.
      • Sum all the partial results.
    2. Part 2:
      • Write a regex that will look for either the exact string as in Part 1 or "do()" or "don't()".
      • Run the regex over the input string and find all matches.
      • Fold over the matches and use the regex from Part 1 to multiply and sum only from the "highlighted" parts of the input string.

    Part 1

    This task plays very well with Scala's strengths: pattern matching and the standard collections library. But first, we need to learn a bit of regular expressions. Personally, I believe everyone should learn them. They're scary only at the beginning, and then they become a very valuable tool in your pocket.

    The shopkeeper at the North Pole Toboggan Rental Shop asks us to go through the input string, find all substrings that look like calls to a multiplication method "mul(a,b)", perform the multiplications, and sum them together. To find such substrings, we will construct a regular expression that will look for the following:

    1. Each substring starts with a text "mul(". We need to escape the parenthesis in the regex form, so this will be mul\(.
    2. "mul(" is followed by the first positive integer. Since it's an integer and positive, we don't need to look for floating points or minuses; we can look for sequences of ciphers. In regex, one cipher is denoted by \d, and since we look for a sequence of one or more ciphers, it's \d+.
    3. After the first number there should be a comma, so ,.
    4. Then there should be a second number, so again \d+.
    5. And the substring should finish with the closing parentheses, escaped again, so \).

    That's it. Our whole regex looks like this:

    val mulPattern: Regex = """mul\((\d+),(\d+)\)""".r

    Given that our input string is already read into the value input, we can now find in it all occurrences of substrings that match our regex:

    val multiplications = mulPattern.findAllIn(input)

    Take note that multiplications is an instance of MatchIterator over the input string. If we turn it into a sequence, it will be a sequence of substrings - but what we actually need to do is extract the numbers from within each substring, multiply them, and then sum them all together. Fortunately, the collect method from the Scala standard collection library will be just perfect for that. What's more, we can reuse the same regex. In Scala, regular expressions can be seamlessly used in pattern matching, which makes working with strings a breeze.

    val result1 = multiplications.collect { case mulPattern(a, b) => a.toInt * b.toInt }.sum

    And here it is - the result for Part 1.

    Part 2

    The second half of the tasks adds a complication. Inside the input string are hidden two more method calls: "do()" and "don't()". The task is to recognize them and perform the multiplication and addition only on those parts of the input strings that are "highlighted". The input string is "highlighted" at the beginning and to the first "don't()". "don't()" turns the highlighting off until we encounter "do()" which turns the highlighting on again. And so on, until the end of the input string.

    To implement this logic, first, we need a slightly more complicated regular expression that matches either "mul(a,b)" or "do()" or "don't()" and can extract from the input string all occurrences of each of those substrings in the order they appear.

    1. We already have the most complicated part of the new regular expressions - it's the regular expression from Part 1, mul\((\d+)\,(\d+)\).
    2. Then, we need to be able to find a text "do()". As we know, we need to escape parentheses, so do\(\).
    3. And similarly, we need to be able to find a substring "don't()" - don't\(\).
    4. Finally, we must tell the compiler we are looking for substrings that match any of the three rules we made above. In regex, this is done by putting regular expressions in parentheses and separating them with a | sign, like this: (GROUP 1|GROUP 2|GROUP 3).

    Together, our new regular expression looks as follows:

    val allPattern: Regex = """(mul\((\d+),(\d+)\)|do\(\)|don't\(\))""".r

    As in Part 1 we can now use allPattern to find all occurences of "mul(a,b)", "do()", and "don't()" in the input string:

    val occurences = allPattern.findAllIn(input)

    But we can't just use collect this time. We need to interate over the sequence of occurences in the order as they appear in the input string, and multiply and add numbers only if they appear in the "highlighted" parts. Let's first go through how to do it using English instead of Scala:

    1. We need a flag that will start "on" (true) and switch it "off" (false) and "on" again as we encounter "don't()"s and "do()"s.
    2. We will also need a sum field — an integer starting at 0 — to which we will add the results of multiplications.
    3. We start in the "highlighted" mode.
    4. If the flag is "on" and we encounter "mul(a,b)", then we extract integers a and b, multiply them, and add them to the sum.
    5. If we encounter "don't()", we switch the flag to "off".
    6. If we encounter "do()", we switch the flag back to "on".
    7. If the flag is "off" and we encounter "mul(a,b)", or if for some reason we can't extract a and b, we do nothing.

    It is theoretically possible that we can encounter consecutive "don't()"s or "do()"s in the input string, but that doesn't change anything - for example, if the flag is "off", and we encounter "don't()", the flag stays "off".

    We can implement this logic with foldLeft. In the first parameter list, our foldLeft will have the initial values of the flag (true) and the sum (0). In the second parameter list, we will provide a function that takes the accumulator - a tuple of the flag and the sum - and each subsequent occurrence of a substring that matches our pattern regular expression. The function will parse the substring and return the updated flag and sum.

    occurences.foldLeft((true, 0)) { ((isHighlighted, sum), substring) => ... }

    But wait, we can use pattern matching again, as in Part 1. We can split that function from the second parameter list into cases, each case implementing one line of logic from our description above:

    occurences.foldLeft((true, 0)) {
    case ((true, sum), mulPattern(a, b)) => (true, sum + (a.toInt * b.toInt)) // line 4
    case ((_, sum), "don't()") => (false, sum) // line 5
    case ((_, sum), "do()") => (true, sum) // line 6
    case ((flag, sum), _) => (flag, sum) // line 7
    }

    That last part in line 7, "if for some reason we can't extract a and b", should never occur because allPattern already guards us against it. However, the Scala compiler does not know that, and without that part, it will warn us that the match may not be exhaustive. The compiler only sees that we use mulPattern in the first case but does not have proof that after checking for it, for "don't()", and for "do()", there are no other cases left.

    Now, the only thing left is to get back the sum after foldLeft iterates over all occurrences of found substrings. foldLeft will return a tuple with the final value of the flag and the sum. We don't need the flag anymore, so we can ignore it:

    val (_, result2) = occurences.foldLeft((true, 0)) { ... }

    Final Code

    import java.nio.file.{Files, Path}
    import scala.util.matching.Regex

    object DayThree:
    private def readInput: String = Files.readString(Path.of("resources/input3"))
    private val mulPattern: Regex = """mul\((\d+),(\d+)\)""".r
    private val allPattern: Regex = """(mul\((\d+),(\d+)\)|do\(\)|don't\(\))""".r

    @main def main(): Unit =
    val input = readInput
    // Part 1
    val res1 = mulPattern.findAllIn(input).collect { case mulPattern(a, b) => a.toInt * b.toInt }.sum
    println(res1)
    // Part 2
    val (_, res2) = allPattern.findAllIn(input).foldLeft((true, 0)) {
    case ((true, sum), mulPattern(a, b)) => (true, sum + (a.toInt * b.toInt))
    case ((_, sum), "don't()") => (false, sum)
    case ((_, sum), "do()") => (true, sum)
    case ((flag, sum), _) => (flag, sum)
    }
    println(res2)

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2024/puzzles/day04/index.html b/2024/puzzles/day04/index.html index 13874ad47..665b002de 100644 --- a/2024/puzzles/day04/index.html +++ b/2024/puzzles/day04/index.html @@ -5,7 +5,7 @@ Day 4: Ceres Search | Scala Center Advent of Code - + @@ -26,7 +26,7 @@ also the center of a valid X-MAS formation. To do this, we will inspect for "MAS" starting in each of the four surrounding corners.

    e.g. if we picture the four corners in the grid like this,

    1-2
    -A-
    4-3

    Then we will look for "MAS" starting from 1 towards 3, from 2 towards 4, from 3 towards 1, and from 4 towards 2.

    To do that we will need two Dirs for each case, one to translate the current point to the corner, and then the opposite direction to scan in. Here is how you can represent that:

    val UpRight = dirs(4)
    val DownRight = dirs(5)
    val DownLeft = dirs(6)
    val UpLeft = dirs(7)

    val dirsMAS = IArray(
    UpLeft -> DownRight, // 1 -> 3
    UpRight -> DownLeft, // 2 -> 4
    DownRight -> UpLeft, // 3 -> 1
    DownLeft -> UpRight // 4 -> 2
    )

    Then to check if a single point is X-MAS, use the following code:

    def isMAS(x: Int, y: Int, grid: Grid): Boolean =
    grid(y)(x) match
    case 'A' =>
    val seen = dirsMAS.count: (transform, dir) =>
    scanMAS(x + transform.dx, y + transform.dy, dir, grid)
    seen > 1
    case _ => false

    i.e. when the point is 'A', then for each of the four corners, translate the point to the corner which will be the origin point to scan for "MAS". Then pass along the scanning direction and the grid. For a valid X-MAS, two of the corners will be origin points for the word.

    Putting it all together, we then again iterate through the grid, now only counting the points where isMas is true.

    def part2(input: String): Int =
    totalMAS(parse(input))

    def totalMAS(grid: Grid): Int =
    Iterator
    .tabulate(grid.size, grid.size): (y, x) =>
    if isMAS(x, y, grid) then 1 else 0
    .flatten
    .sum

    Final Code

    def part1(input: String): Int =
    totalXMAS(parse(input))

    type Grid = IArray[IArray[Char]]

    def parse(input: String): Grid =
    IArray.from(
    input.linesIterator.map(IArray.from)
    )

    case class Dir(dy: Int, dx: Int)

    val dirs = IArray(
    Dir(dy = -1, dx = 0), // up
    Dir(dy = 0, dx = 1), // right
    Dir(dy = 1, dx = 0), // down
    Dir(dy = 0, dx = -1), // left
    Dir(dy = -1, dx = 1), // up-right
    Dir(dy = 1, dx = 1), // down-right
    Dir(dy = 1, dx = -1), // down-left
    Dir(dy = -1, dx = -1) // up-left
    )

    def boundCheck(x: Int, y: Int, grid: Grid): Boolean =
    x >= 0 && x < grid.length && y >= 0 && y < grid(0).length

    def scanner(x: Int, y: Int, dir: Dir, grid: Grid): Iterator[Char] =
    Iterator.unfold((y, x)): (y, x) =>
    Option.when(boundCheck(x, y, grid))(grid(y)(x) -> (y + dir.dy, x + dir.dx))

    def scanString(target: String)(x: Int, y: Int, dir: Dir, grid: Grid): Boolean =
    scanner(x, y, dir, grid).take(target.length).corresponds(target)(_ == _)

    val scanXMAS = scanString("XMAS")

    def totalXMAS(grid: Grid): Int =
    Iterator
    .tabulate(grid.size, grid.size): (y, x) =>
    dirs.count(dir => scanXMAS(x, y, dir, grid))
    .flatten
    .sum

    def part2(input: String): Int =
    totalMAS(parse(input))

    val scanMAS = scanString("MAS")

    val UpRight = dirs(4)
    val DownRight = dirs(5)
    val DownLeft = dirs(6)
    val UpLeft = dirs(7)

    val dirsMAS = IArray(
    UpLeft -> DownRight,
    UpRight -> DownLeft,
    DownRight -> UpLeft,
    DownLeft -> UpRight
    )

    def isMAS(x: Int, y: Int, grid: Grid): Boolean =
    grid(y)(x) match
    case 'A' =>
    val seen = dirsMAS.count: (transform, dir) =>
    scanMAS(x + transform.dx, y + transform.dy, dir, grid)
    seen > 1
    case _ => false

    def totalMAS(grid: Grid): Int =
    Iterator
    .tabulate(grid.size, grid.size): (y, x) =>
    if isMAS(x, y, grid) then 1 else 0
    .flatten
    .sum

    Solutions from the community

    - + \ No newline at end of file diff --git a/2024/puzzles/day05/index.html b/2024/puzzles/day05/index.html index d2fd6b30c..66443fb70 100644 --- a/2024/puzzles/day05/index.html +++ b/2024/puzzles/day05/index.html @@ -5,14 +5,14 @@ Day 5: Print Queue | Scala Center Advent of Code - +
    Skip to main content

    Day 5: Print Queue

    by @KacperFKorban

    Puzzle description

    https://adventofcode.com/2024/day/5

    Solution Summary

    We can treat the data as a graph, where:

    • the ordering rules represent directed edges in the graph
    • each update represents a subset of the nodes

    As a common part of the solution, we will:

    • parse the input into a list of ordering rules (Int, Int) and a list of updates List[List[Int]]
    • represent the rules as an adjacency list Map[Int, List[Int]]
    1. Part 1:
      • For every update, we iterate over its elements (while keeping track of the visited nodes) and for each node check that none of its successors were visited before it.
      • We only keep the updates that don't violate the ordering rules.
      • We compute the middle number of the valid updates.
      • The solution is the sum of the middle numbers of the valid updates.
    2. Part 2:
      • Similarily to part 1, we iterate over the updates and check if the ordering rules are violated, but this time we only keep the updates that do violate the ordering rules.
      • To fix the ordering for each update:
        • We find the nodes that have no incoming edges.
        • Then, we run a BFS starting from these nodes, making sure that we only enqueue nodes when all of their incoming edges have been visited or enqueued.

    Common part

    For both parts of the solution, we will parse the input into an adjacency list and a list of updates.

    def parseRulesAndupdates(input: String): (Map[Int, List[Int]], List[List[Int]]) =
    val ruleRegex: Regex = """(\d+)\|(\d+)""".r
    val Array(rulesStr, updatesStr) = input.split("\n\n")
    val rules: Map[Int, List[Int]] =
    ruleRegex.findAllMatchIn(rulesStr).map { m =>
    m.group(1).toInt -> m.group(2).toInt
    }.toList.groupMap(_._1)(_._2)
    val updates: List[List[Int]] =
    updatesStr.linesIterator.map(_.split(",").map(_.toInt).toList).toList
    (rules, updates)

    We first split the input into two parts. Then, for rules we convert them into a list of pairs (Int, Int) using a regex and group them by the first element. For updates, we simply split them by commas and convert the elements to Ints.

    Part 1

    To check if an update is valid, we iterate over the elements of the update and check if none of the neighbors of the current node were visited before it.

    This can be done in several ways, for example by using a recursive function:

    def isValid(rules: Map[Int, List[Int]])(update: List[Int]): Boolean =
    def rec(update: List[Int], visited: Set[Int] = Set.empty): Boolean = update match
    case Nil => true
    case updateNo :: rest =>
    !rules.getOrElse(updateNo, List.empty).exists(visited.contains)
    && rec(rest, visited + updateNo)
    rec(update)

    another alternative is using boundary-break with a for:

    def isValid(rules: Map[Int, List[Int]])(update: List[Int]): Boolean =
    boundary:
    var visited = Set.empty[Int]
    for updateNo <- update do
    visited += updateNo
    if rules.getOrElse(updateNo, List.empty).exists(visited.contains) then
    break(false)
    true

    or a forall with a local mutable state:

    def isValid(rules: Map[Int, List[Int]])(update: List[Int]): Boolean =
    var visited = Set.empty[Int]
    update.forall { updateNo =>
    visited += updateNo
    !rules.getOrElse(updateNo, List.empty).exists(visited.contains)
    }

    Using the isValid function, we can filter the updates and compute the middle number of the valid updates:

    def part1(input: String) =
    val (rules, updates) = parseRulesAndupdates(input)
    updates.filter(isValid(rules)).map(us => us(us.size / 2)).sum

    Part 2

    We start Part 2 by parsing and filtering the updates that violate the ordering rules, very similarly to Part 1:

    val (rules, updates) = parseRulesAndupdates(input)
    val invalidupdates = updates.filter(!isValid(rules)(_))

    Next, to fix a single update, we first construct local adjacency lists for the relevant nodes and an inverse adjacency list to keep track of the incoming edges:

    def fixUpdate(update: List[Int]): List[Int] =
    val relevantRules = rules
    .filter((k, vs) => update.contains(k) && vs.exists(update.contains))
    .mapValues(_.filter(update.contains)).toMap
    val prevsMap = relevantRules
    .map { case (k, vs) => vs.map(_ -> k) }
    .flatten.groupMap(_._1)(_._2)

    The relevantRules are only those that only use the nodes from update, and the prevsMap is a map from a node to its direct predecessors.

    Then, we start with nodes that have no incoming edges and run a BFS to fix the ordering:

    val startNodes = update.filter(k => !relevantRules.values.flatten.toList.contains(k))

    The BFS function takes a set of visited nodes, a queue of nodes to visit, and a list of nodes in the correct order:

      def bfs(queue: Queue[Int], visited: Set[Int] = Set.empty, res: List[Int] = List.empty): List[Int] = queue.dequeueOption match
    case None => res
    case Some((node, queue1)) =>
    val newVisited = visited + node
    val newRes = res :+ node
    val newQueue = relevantRules.getOrElse(node, List.empty)
    .filter { n =>
    val notVisited = !newVisited.contains(n)
    val notInQueue = !queue1.contains(n)
    val allPrevVisited = prevsMap.getOrElse(n, List.empty).forall(p => newVisited.contains(p) || queue1.contains(p))
    notVisited && notInQueue && allPrevVisited
    }
    .foldLeft(queue1)(_.appended(_))
    bfs(newVisited, newQueue, newRes)

    The BFS works as follows:

    • If the queue is empty, we return the result

    • Otherwise, we dequeue a node and add it to the visited set and the result list. We enqueue all neighbors of the node that:

      • have not been visited yet
      • and are not in the queue
      • and have all of their incoming edges visited or enqueued.

      We then call the BFS function recursively with the updated queue, visited set, and result list.

    The result of the fixUpdate function is call to the bfs function with the startNodes in the queue.

    The solution for part2 is then a sum of the middle numbers of the fixed updates:

    invalidUpdates.map(fixUpdate).map(us => us(us.size / 2)).sum

    The full solution for Part 2 looks like this:


    def part2(input: String) =
    val (rules, updates) = parseRulesAndupdates(input)
    val invalidUpdates = updates.filter(!isValid(rules)(_))

    def fixUpdate(update: List[Int]): List[Int] =
    val relevantRules = rules
    .filter((k, vs) => update.contains(k) && vs.exists(update.contains))
    .mapValues(_.filter(update.contains)).toMap
    val prevsMap = relevantRules
    .map { case (k, vs) => vs.map(_ -> k) }
    .flatten.groupMap(_._1)(_._2)
    val startNodes = update.filter(k => !relevantRules.values.flatten.toList.contains(k))
    def bfs(queue: Queue[Int], visited: Set[Int] = Set.empty, res: List[Int] = List.empty): List[Int] = queue.dequeueOption match
    case None => res
    case Some((node, queue1)) =>
    val newVisited = visited + node
    val newRes = res :+ node
    val newQueue = relevantRules.getOrElse(node, List.empty)
    .filter { n =>
    val notVisited = !newVisited.contains(n)
    val notInQueue = !queue1.contains(n)
    val allPrevVisited = prevsMap.getOrElse(n, List.empty).forall(p => newVisited.contains(p) || queue1.contains(p))
    notVisited && notInQueue && allPrevVisited
    }
    .foldLeft(queue1)(_.appended(_))
    bfs(newQueue, newVisited, newRes)
    bfs(Queue.from(startNodes))

    invalidUpdates.map(fixUpdate).map(us => us(us.size / 2)).sum

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2024/puzzles/day06/index.html b/2024/puzzles/day06/index.html index d2cf3efed..b34d59e27 100644 --- a/2024/puzzles/day06/index.html +++ b/2024/puzzles/day06/index.html @@ -5,7 +5,7 @@ Day 6: Guard Gallivant | Scala Center Advent of Code - + @@ -15,7 +15,7 @@ Please note that we could detect the loop with a smaller path, for example, by checking when we detect a point of view that was already visited. However, this is a simple and elegant solution that works well for the input size.

    So we define a looping function as follows:

    def looping(guard: Guard, startingPov: PointOfView): Boolean = 
    val followedPath = guard.simulateWithinLab(startingPov).take(guard.lab.eastWestLength * guard.lab.northSouthLength + 1)
    followedPath.size >= guard.lab.eastWestLength * guard.lab.northSouthLength

    To make sure the function terminates, we can take() with the minimum number of steps we require to detect a loop, which is the total area of the lab + 1. So the returned path will have at most this length. Remember that the LazyList is infinite in the case of looping, so if we just check the length of the path, the function will not terminate.

    Once we have a function to detect whether the guard loops or not given a lab disposition and starting position, we can write a function that computes how many different obstacle positions lead to a looping guard.

    To do so, we will create a list of all possible obstacle positions, which are all positions in the lab except for the starting position, and create copies of the lab with an obstacle in each of these positions. We then count how many of those lead to a looping guard:

    def possibleObstaclesPositionsNumber(g: Guard, startingPov: PointOfView): Int = 
    val possibleObstaclesPositions =
    (
    for
    x <- 0 to g.lab.eastWestLength
    y <- 0 to g.lab.northSouthLength
    if g.lab.isWithinLab(x, y) && (x, y) != startingPov._1
    yield (x, y)
    )

    val newPossibleGuards=
    possibleObstaclesPositions.map(obstaclePos =>
    val newLab = g.lab.replaceWith(obstaclePos._1, obstaclePos._2, '#')
    Guard(newLab)
    )

    newPossibleGuards.par.count(g => looping(g, startingPov))

    As we are brute forcing, let's use a parallel collection, to use all the potential of our nice hardware, to check multiple lab dispositions at the same time. We also use a ForkJoinPool to control the number of threads used by the parallel collection. See how simple it is to use parallel collections in Scala, using the .par method.

    This concludes the solution for part 2 of the problem.

    https://adventofcode.com/2024/day/6

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2024/puzzles/day07/index.html b/2024/puzzles/day07/index.html index 1af656081..ccb974337 100644 --- a/2024/puzzles/day07/index.html +++ b/2024/puzzles/day07/index.html @@ -5,7 +5,7 @@ Day 7: Bridge Repair | Scala Center Advent of Code - + @@ -23,7 +23,7 @@ the checkEquation function.

    We add a withConcat parameter to the checkEquation function, so that we can use the same function for both parts 1 and 2.

    def checkEquation(testValue: Long, numbers: List[Long], withConcat: Boolean = false): Boolean =
    numbers match {
    case fst :: Nil =>
    fst == testValue
    case fst :: snd :: rest =>
    checkEquation(testValue, (fst * snd) :: rest, withConcat) || checkEquation(testValue, (fst + snd) :: rest, withConcat) ||
    (withConcat && checkEquation(testValue, (fst.toString ++ snd.toString).toLong :: rest, withConcat))
    }

    def part2(input: String): Long =
    val equations = parse(input)
    equations.map:
    case (testValue, numbers) =>
    if checkEquation(testValue, numbers, withConcat = true) then testValue else 0L
    .sum
    end part2

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2024/puzzles/day08/index.html b/2024/puzzles/day08/index.html index d6fb32fcb..9f49a8425 100644 --- a/2024/puzzles/day08/index.html +++ b/2024/puzzles/day08/index.html @@ -5,7 +5,7 @@ Day 8: Resonant Collinearity | Scala Center Advent of Code - + @@ -34,7 +34,7 @@ Iterator.iterate to generate the infinite series of these locations and then just take while the location is within the map.

    def part2(input: String): String =
    val map = parse(input)

    val antinodes: Iterable[Location] = for
    antennaGroup <- map.antennaGroups
    case a +: b +: _ <- antennaGroup.combinations(2)
    antinode <- Iterator.iterate(a)(_ + (a - b)).takeWhile(_.within(map)) ++
    Iterator.iterate(b)(_ + (b - a)).takeWhile(_.within(map))
    yield antinode

    antinodes.toSet.size.toString
    end part2

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2024/puzzles/day09/index.html b/2024/puzzles/day09/index.html index 1b56f3d2d..e59f22226 100644 --- a/2024/puzzles/day09/index.html +++ b/2024/puzzles/day09/index.html @@ -5,13 +5,13 @@ Day 9: Disk Fragmenter | Scala Center Advent of Code - +
    Skip to main content

    Day 9: Disk Fragmenter

    by @dyvrl

    Puzzle description

    https://adventofcode.com/2024/day/9

    Solution Summary

    1. Convert the input to a disk representation:
    • part1: A sequence of optional file indices
    • part2: A sequence of indivisible file/free-space blocks
    1. Create a compact representation of this disk: Starting from the end of the disk,
    • part1: Move individual file indices to the leftmost free space
    • part2: Move file blocks to the to the leftmost free block, if any
    1. Compute the checksum of the resulting disk

    Part 1

    Each part will define its own Disk type. For part1, this will simply be a Seq[Option[Int]], where each charater has an assigned value:

    • Some(index) for file blocks, with their corresponding index
    • None for free blocks

    Our main driver converts the input to a Disk, create a new compact Disk from it and finally computes its checksum

    def part1(input: String): Long =

    type Disk = Seq[Option[Int]]
    extension(disk: Disk)
    def checksum: Long = ???

    def createDisk(input: String): Disk = ???

    def compact(disk: Disk): Disk = ???

    val disk = createDisk(input)
    compact(disk).checksum

    Let's first implement checksum: It is the sum of each file ID times its position in the disk

    extension(disk: Disk)
    def checksum: Long = disk
    .zipWithIndex
    .map(_.getOrElse(0).toLong * _) // Free blocks are mapped to 0
    .sum

    To create our disk from the input, we need to:

    • Convert our input to a List[Int] ranging from 0 to 9
    • Group elements 2 by 2 to create pairs of (file, free) blocks count
    • Zip these groups with their indices
    • Unroll these pairs into an actual sequence with the correct number of elements
    • Concatenate these newly created sequences
    def createDisk(input: String): Disk =
    val intInput = input.toList.map(_ - '0') // Convert characters to int [0, 9]
    val fileFreeGroups = intInput.grouped(2).toVector // Last group will contain a single element
    val zippedGroups = fileFreeGroups.zipWithIndex
    zippedGroups.flatMap:
    case (List(fileN, freeN), i) =>
    // File block followed by free block
    List.fill(fileN)(Some(i)) ::: List.fill(freeN)(None)
    case (List(fileN), i) =>
    // Final file block
    List.fill(fileN)(Some(i))
    case _ => Nil

    Finally, we need to compact the disk we obtain: Iterate over the disk elements, from the beginning (left)

    • If we encounter a free block: replace it with the last element in the disk and repeat the recursion
    • If we encounter a file block: Append it to the result and continue with the next element in the disk

    All of this can be implemented using a tail-recursive function:

    def compact(disk: Disk): Disk =
    @tailrec
    def compactRec(disk: Disk, acc: Disk): Disk =
    if disk.isEmpty then
    acc
    else
    disk.head match
    case None => compactRec(disk.last +: disk.tail.init, acc) // Take the last element, put it first and eliminate free block
    case file@Some(_) => compactRec(disk.tail, acc :+ file) // Append the file block
    compactRec(disk, Vector.empty)

    Part 2

    The code remains very similar to part1. However this time, the Disk structure can't consider characters individually anymore. Consecutive file blocks are indivisible, they form a single Block. Thus, we define a new Block enumeration. All Blocks have a size, but Free blocks do not have any index attached whereas File blocks do:

    enum Block(val size: Int):
    case Free(s: Int) extends Block(s)
    case File(s: Int, i: Int) extends Block(s)

    def index = this match
    case Free(size) => None
    case File(size, id) => Some(id)

    The main driver for part2 has the same components as the one from part1:

    • checksum remains unchanged (except to convert our new Disk to the previous Disk)
    • createDisk produces a sequence of blocks instead of flattening every character into a single sequence
    def part2(input: String): Long =

    enum Block(val size: Int):
    case Free(s: Int) extends Block(s)
    case File(s: Int, i: Int) extends Block(s)

    def index = this match
    case Free(size) => None
    case File(size, id) => Some(id)
    // [...]

    type Disk = Seq[Block]
    extension(disk: Disk)
    def checksum: Long = disk
    .flatMap(b => Vector.fill(b.size)(b.index.getOrElse(0))) // Convert to previous `Disk`
    .zipWithIndex
    .map(_.toLong * _)
    .sum

    def createDisk(input: String): Disk =
    val intInput = input.toList.map(_ - '0') // Convert characters to int [0, 9]
    val fileFreeGroups = intInput.grouped(2).toVector // Last group will contain a single element
    val zippedGroups = fileFreeGroups.zipWithIndex
    zippedGroups.flatMap:
    case (List(fileN, freeN), id) =>
    Vector(Block.File(fileN, id), Block.Free(freeN))
    case (List(fileN), id) =>
    Vector(Block.File(fileN, id))
    case _ => Nil

    def compact(disk: Disk): Disk = ???

    val disk = createDisk(input)
    compact(disk).checksum

    This time, the compact method needs to keep contiguous file blocks in one piece. Iterate over the blocks of the disk, starting from the right:

    • If we encounter a free block, we prepend it to the result
    • If we encounter a file block, we find the leftmost free block large enough to insert file block:
      • If we couldn't find any such free block, prepend the file block to the result
      • Otherwise, insert the file block inside the found free block. This creates a new view of our disk that we will use for subsequent iterations. Prepend a free block of the same size as the file block to the result.

    Again, this can be implemented using a tail-recursive function:

    def compact(disk: Disk): Disk =
    @tailrec
    def compactRec(disk: Disk, acc: Disk): Disk =
    disk.lastOption match
    case None =>
    acc
    case Some(last@Block.Free(_)) =>
    // Free blocks are not moved
    compactRec(disk.init, last +: acc)
    case Some(last@Block.File(size, _)) =>
    // Find first block which can fit the file block
    val fitter = disk
    .zipWithIndex
    .find((block, _) => block.canInsert(last))

    fitter match
    case None =>
    // If it doesn't fit anywhere, don't move it
    compactRec(disk.init, last +: acc)
    case Some(free@Block.Free(_), id) =>
    // If it fits somewhere, insert inside this free block
    val newDisk = disk.take(id) ++ free.insert(last) ++ disk.drop(id+1).init
    compactRec(newDisk, Block.Free(last.size) +: acc)
    case _ => throw new MatchError("Unexpected block type")
    compactRec(disk, Vector.empty)

    Where we defined some auxiliary methods on Blocks to simplify the code:

    enum Block(val size: Int):
    // [...]
    def canInsert(block: Block) = this match
    case Free(size) => size >= block.size
    case _ => false

    extension (free: Block.Free)
    def insert(b: Block): Seq[Block] =
    if b.size < free.size then
    Seq(b, Block.Free(free.size-b.size))
    else
    Seq(b)

    Final code

    def part1(input: String): Long =

    type Disk = Seq[Option[Int]]
    extension(disk: Disk)
    def checksum: Long = disk
    .zipWithIndex
    .map(_.getOrElse(0).toLong * _) // Free blocks are mapped to 0
    .sum

    def createDisk(input: String): Disk =
    val intInput = input.toList.map(_ - '0') // Convert characters to int [0, 9]
    val fileFreeGroups = intInput.grouped(2).toVector // Last group will contain a single element
    val zippedGroups = fileFreeGroups.zipWithIndex
    val disk = zippedGroups.flatMap:
    case (List(fileN, freeN), i) =>
    // File block followed by free block
    List.fill(fileN)(Some(i)) ::: List.fill(freeN)(None)
    case (List(fileN), i) =>
    // Final file block
    List.fill(fileN)(Some(i))
    case _ => Nil
    return disk

    def compact(disk: Disk): Disk =
    @tailrec
    def compactRec(disk: Disk, acc: Disk): Disk =
    if disk.isEmpty then
    acc
    else
    disk.head match
    case None => compactRec(disk.last +: disk.tail.init, acc) // Take the last element, put it first and eliminate free block
    case file@Some(_) => compactRec(disk.tail, acc :+ file) // Append the file block
    compactRec(disk, Vector.empty)

    val disk = createDisk(input)
    compact(disk).checksum

    def part2(input: String): Long =

    enum Block(val size: Int):
    case Free(s: Int) extends Block(s)
    case File(s: Int, i: Int) extends Block(s)

    def index = this match
    case Free(size) => None
    case File(size, id) => Some(id)

    def canInsert(block: Block) = this match
    case Free(size) => size >= block.size
    case _ => false

    extension (free: Block.Free)
    def insert(b: Block): Seq[Block] =
    if b.size < free.size then
    Seq(b, Block.Free(free.size-b.size))
    else
    Seq(b)

    type Disk = Seq[Block]
    extension(disk: Disk)
    def checksum: Long = disk
    .flatMap(b => Vector.fill(b.size)(b.index.getOrElse(0))) // Convert to previous `Disk`
    .zipWithIndex
    .map(_.toLong * _)
    .sum

    def createDisk(input: String): Disk =
    val intInput = input.toList.map(_ - '0') // Convert characters to int [0, 9]
    val fileFreeGroups = intInput.grouped(2).toVector // Last group will contain a single element
    val zippedGroups = fileFreeGroups.zipWithIndex
    val disk = zippedGroups.flatMap:
    case (List(fileN, freeN), id) =>
    Vector(Block.File(fileN, id), Block.Free(freeN))
    case (List(fileN), id) =>
    Vector(Block.File(fileN, id))
    case _ => Nil
    return disk

    def compact(disk: Disk): Disk =
    @tailrec
    def compactRec(disk: Disk, acc: Disk): Disk = disk.lastOption match
    case None =>
    acc
    case Some(last@Block.Free(_)) =>
    // Free blocks are not moved
    compactRec(disk.init, last +: acc)
    case Some(last@Block.File(size, _)) =>
    // Find first block in which we can insert the file block
    val fitter = disk
    .zipWithIndex
    .find((block, _) => block.canInsert(last))

    fitter match
    case None =>
    // If it doesn't fit anywhere, don't move it
    compactRec(disk.init, last +: acc)
    case Some(free@Block.Free(_), id) =>
    // If it fits somewhere, insert inside this free block
    val newDisk = disk.take(id) ++ free.insert(last) ++ disk.drop(id+1).init
    compactRec(newDisk, Block.Free(last.size) +: acc)
    case _ => throw new MatchError("Unexpected block type")
    compactRec(disk, Vector.empty)

    val disk = createDisk(input)
    compact(disk).checksum

    Run it in the browser

    Part 1

    Part 2

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/2024/puzzles/day10/index.html b/2024/puzzles/day10/index.html index 9f428a3db..ce288ceb3 100644 --- a/2024/puzzles/day10/index.html +++ b/2024/puzzles/day10/index.html @@ -5,7 +5,7 @@ Day 10: Hoof It | Scala Center Advent of Code - + @@ -34,9 +34,9 @@ with part 1, but I've chosen to leave it this way.

      def solve2(topo: Topo): Int =
    val graph = computeGraph(topo)
    def routes(pos: Pos): Int =
    if topo(pos) == 9
    then 1
    else graph(pos).toSeq.map(routes).sum
    topo.positions
    .filter(pos => topo(pos) == 0)
    .map(routes)
    .sum

    def part2(name: String): Int =
    solve2(getInput(name))

    One tricky bit here is the necessity to include toSeq when recursing. That's because we have a Set[Pos], but if we .map(...) on a Set, the result will also be a Set. But we don't want to -throw away duplicate counts.

    Solutions from the community

    Share your solution to the Scala community by editing this page. +throw away duplicate counts.

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/2024/puzzles/day11/index.html b/2024/puzzles/day11/index.html index 20b5a4cf8..ee98ed637 100644 --- a/2024/puzzles/day11/index.html +++ b/2024/puzzles/day11/index.html @@ -5,14 +5,14 @@ Day 11: Plutonian Pebbles | Scala Center Advent of Code - +
    -
    Skip to main content

    Day 11: Plutonian Pebbles

    Puzzle description

    https://adventofcode.com/2024/day/11

    Solutions from the community

    Share your solution to the Scala community by editing this page. +

    - + \ No newline at end of file diff --git a/404.html b/404.html index 6111401cc..2cb9271a3 100644 --- a/404.html +++ b/404.html @@ -5,13 +5,13 @@ Page Not Found | Scala Center Advent of Code - + - + \ No newline at end of file diff --git a/assets/js/a1a15f20.5d2da92b.js b/assets/js/a1a15f20.c7225a78.js similarity index 77% rename from assets/js/a1a15f20.5d2da92b.js rename to assets/js/a1a15f20.c7225a78.js index 3d6bcdd47..342a9511c 100644 --- a/assets/js/a1a15f20.5d2da92b.js +++ b/assets/js/a1a15f20.c7225a78.js @@ -1 +1 @@ -"use strict";(self.webpackChunkwebsite=self.webpackChunkwebsite||[]).push([[4104],{105:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>r,contentTitle:()=>l,default:()=>p,frontMatter:()=>n,metadata:()=>s,toc:()=>c});var o=a(7462),i=(a(7294),a(3905));a(6340);const n={},l="Day 11: Plutonian Pebbles",s={unversionedId:"2024/puzzles/day11",id:"2024/puzzles/day11",title:"Day 11: Plutonian Pebbles",description:"Puzzle description",source:"@site/target/mdoc/2024/puzzles/day11.md",sourceDirName:"2024/puzzles",slug:"/2024/puzzles/day11",permalink:"/scala-advent-of-code/2024/puzzles/day11",draft:!1,editUrl:"https://github.com/scalacenter/scala-advent-of-code/edit/website/docs/2024/puzzles/day11.md",tags:[],version:"current",frontMatter:{},sidebar:"adventOfCodeSidebar",previous:{title:"Day 10: Hoof It",permalink:"/scala-advent-of-code/2024/puzzles/day10"},next:{title:"Day 1: Trebuchet?!",permalink:"/scala-advent-of-code/2023/puzzles/day01"}},r={},c=[{value:"Puzzle description",id:"puzzle-description",level:2},{value:"Solutions from the community",id:"solutions-from-the-community",level:2}],u={toc:c};function p(e){let{components:t,...a}=e;return(0,i.kt)("wrapper",(0,o.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h1",{id:"day-11-plutonian-pebbles"},"Day 11: Plutonian Pebbles"),(0,i.kt)("h2",{id:"puzzle-description"},"Puzzle description"),(0,i.kt)("p",null,(0,i.kt)("a",{parentName:"p",href:"https://adventofcode.com/2024/day/11"},"https://adventofcode.com/2024/day/11")),(0,i.kt)("h2",{id:"solutions-from-the-community"},"Solutions from the community"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"https://github.com/nikiforo/aoc24/blob/main/src/main/scala/io/github/nikiforo/aoc24/D11T2.scala"},"Solution")," by ",(0,i.kt)("a",{parentName:"li",href:"https://github.com/nikiforo"},"Artem Nikiforov")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"https://github.com/bishabosha/advent-of-code-2024/blob/main/2024-day11.scala"},"Solution")," by ",(0,i.kt)("a",{parentName:"li",href:"https://github.com/bishabosha"},"Jamie Thompson")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"https://github.com/spamegg1/aoc/blob/master/2024/11/11.worksheet.sc#L80"},"Solution")," by ",(0,i.kt)("a",{parentName:"li",href:"https://github.com/spamegg1"},"Spamegg")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"https://github.com/rmarbeck/advent2024/blob/main/day11/src/main/scala/Solution.scala"},"Solution")," by ",(0,i.kt)("a",{parentName:"li",href:"https://github.com/rmarbeck"},"Rapha\xebl Marbeck")," ")),(0,i.kt)("p",null,"Share your solution to the Scala community by editing this page.\nYou can even write the whole article! ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/scalacenter/scala-advent-of-code/discussions/424"},"See here for the expected format")))}p.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunkwebsite=self.webpackChunkwebsite||[]).push([[4104],{105:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>r,contentTitle:()=>n,default:()=>p,frontMatter:()=>l,metadata:()=>s,toc:()=>c});var o=a(7462),i=(a(7294),a(3905));a(6340);const l={},n="Day 11: Plutonian Pebbles",s={unversionedId:"2024/puzzles/day11",id:"2024/puzzles/day11",title:"Day 11: Plutonian Pebbles",description:"Puzzle description",source:"@site/target/mdoc/2024/puzzles/day11.md",sourceDirName:"2024/puzzles",slug:"/2024/puzzles/day11",permalink:"/scala-advent-of-code/2024/puzzles/day11",draft:!1,editUrl:"https://github.com/scalacenter/scala-advent-of-code/edit/website/docs/2024/puzzles/day11.md",tags:[],version:"current",frontMatter:{},sidebar:"adventOfCodeSidebar",previous:{title:"Day 10: Hoof It",permalink:"/scala-advent-of-code/2024/puzzles/day10"},next:{title:"Day 1: Trebuchet?!",permalink:"/scala-advent-of-code/2023/puzzles/day01"}},r={},c=[{value:"Puzzle description",id:"puzzle-description",level:2},{value:"Solutions from the community",id:"solutions-from-the-community",level:2}],u={toc:c};function p(e){let{components:t,...a}=e;return(0,i.kt)("wrapper",(0,o.Z)({},u,a,{components:t,mdxType:"MDXLayout"}),(0,i.kt)("h1",{id:"day-11-plutonian-pebbles"},"Day 11: Plutonian Pebbles"),(0,i.kt)("h2",{id:"puzzle-description"},"Puzzle description"),(0,i.kt)("p",null,(0,i.kt)("a",{parentName:"p",href:"https://adventofcode.com/2024/day/11"},"https://adventofcode.com/2024/day/11")),(0,i.kt)("h2",{id:"solutions-from-the-community"},"Solutions from the community"),(0,i.kt)("ul",null,(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"https://github.com/nikiforo/aoc24/blob/main/src/main/scala/io/github/nikiforo/aoc24/D11T2.scala"},"Solution")," by ",(0,i.kt)("a",{parentName:"li",href:"https://github.com/nikiforo"},"Artem Nikiforov")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"https://github.com/bishabosha/advent-of-code-2024/blob/main/2024-day11.scala"},"Solution")," by ",(0,i.kt)("a",{parentName:"li",href:"https://github.com/bishabosha"},"Jamie Thompson")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"https://github.com/spamegg1/aoc/blob/master/2024/11/11.worksheet.sc#L80"},"Solution")," by ",(0,i.kt)("a",{parentName:"li",href:"https://github.com/spamegg1"},"Spamegg")),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"https://github.com/rmarbeck/advent2024/blob/main/day11/src/main/scala/Solution.scala"},"Solution")," by ",(0,i.kt)("a",{parentName:"li",href:"https://github.com/rmarbeck"},"Rapha\xebl Marbeck")," "),(0,i.kt)("li",{parentName:"ul"},(0,i.kt)("a",{parentName:"li",href:"https://github.com/scarf005/aoc-scala/blob/main/2024/day11.scala"},"Solution")," by ",(0,i.kt)("a",{parentName:"li",href:"https://github.com/scarf005"},"scarf"))),(0,i.kt)("p",null,"Share your solution to the Scala community by editing this page.\nYou can even write the whole article! ",(0,i.kt)("a",{parentName:"p",href:"https://github.com/scalacenter/scala-advent-of-code/discussions/424"},"See here for the expected format")))}p.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/b84e93db.16b2ef16.js b/assets/js/b84e93db.a14062b6.js similarity index 94% rename from assets/js/b84e93db.16b2ef16.js rename to assets/js/b84e93db.a14062b6.js index 9edc8e3cc..0d1b4991b 100644 --- a/assets/js/b84e93db.16b2ef16.js +++ b/assets/js/b84e93db.a14062b6.js @@ -1 +1 @@ -"use strict";(self.webpackChunkwebsite=self.webpackChunkwebsite||[]).push([[2999],{4410:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>c,frontMatter:()=>i,metadata:()=>r,toc:()=>p});var o=a(7462),n=(a(7294),a(3905));a(6340);const i={},s="Day 10: Hoof It",r={unversionedId:"2024/puzzles/day10",id:"2024/puzzles/day10",title:"Day 10: Hoof It",description:"by @SethTisue",source:"@site/target/mdoc/2024/puzzles/day10.md",sourceDirName:"2024/puzzles",slug:"/2024/puzzles/day10",permalink:"/scala-advent-of-code/2024/puzzles/day10",draft:!1,editUrl:"https://github.com/scalacenter/scala-advent-of-code/edit/website/docs/2024/puzzles/day10.md",tags:[],version:"current",frontMatter:{},sidebar:"adventOfCodeSidebar",previous:{title:"Day 9: Disk Fragmenter",permalink:"/scala-advent-of-code/2024/puzzles/day09"},next:{title:"Day 11: Plutonian Pebbles",permalink:"/scala-advent-of-code/2024/puzzles/day11"}},l={},p=[{value:"Puzzle description",id:"puzzle-description",level:2},{value:"Summary",id:"summary",level:2},{value:"Shared code",id:"shared-code",level:3},{value:"Part 1",id:"part-1",level:3},{value:"Part 2",id:"part-2",level:3},{value:"Solutions from the community",id:"solutions-from-the-community",level:2}],h={toc:p};function c(e){let{components:t,...a}=e;return(0,n.kt)("wrapper",(0,o.Z)({},h,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("h1",{id:"day-10-hoof-it"},"Day 10: Hoof It"),(0,n.kt)("p",null,"by ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/SethTisue"},"@SethTisue")),(0,n.kt)("h2",{id:"puzzle-description"},"Puzzle description"),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://adventofcode.com/2024/day/10"},"https://adventofcode.com/2024/day/10")),(0,n.kt)("h2",{id:"summary"},"Summary"),(0,n.kt)("p",null,"Like many Advent of Code puzzles, this is a graph search problem.\nSuch problems are highly amenable to recursive solutions."),(0,n.kt)("p",null,"In large graphs, it may be necessary to memoize intermediate results\nin order to get good performance. But here, it turns out that the\ngraphs are small enough that recursion alone does the job just fine."),(0,n.kt)("h3",{id:"shared-code"},"Shared code"),(0,n.kt)("p",null,"Let's start by representing coordinate pairs:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-scala"}," type Pos = (Int, Int)\n extension (pos: Pos)\n def +(other: Pos): Pos =\n (pos(0) + other(0), pos(1) + other(1))\n")),(0,n.kt)("p",null,"and the input grid:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-scala"}," type Topo = Vector[Vector[Int]]\n extension (topo: Topo)\n def apply(pos: Pos): Int =\n topo(pos(0))(pos(1))\n def inBounds(pos: Pos): Boolean =\n pos(0) >= 0 && pos(0) < topo.size &&\n pos(1) >= 0 && pos(1) < topo.head.size\n def positions =\n for row <- topo.indices\n column <- topo.head.indices\n yield (row, column)\n")),(0,n.kt)("p",null,"So far this is all quite typical code that is usable in many\nAdvent of Code puzzles."),(0,n.kt)("p",null,"Reading the input is typical as well:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-scala"}," def getInput(name: String): Topo =\n io.Source.fromResource(name)\n .getLines\n .map(_.map(_.asDigit).toVector)\n .toVector\n")),(0,n.kt)("p",null,'In order to avoid doing coordinate math all the time, let\'s turn the\ngrid into a graph by analyzing which cells are actually connected to\neach other. Each cell can only have a small number of "reachable"\nneighbors -- those neighbors that are exactly 1 higher than us.'),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-scala"}," type Graph = Map[Pos, Set[Pos]]\n\n def computeGraph(topo: Topo): Graph =\n def reachableNeighbors(pos: Pos): Set[Pos] =\n Set((-1, 0), (1, 0), (0, -1), (0, 1))\n .flatMap: offsets =>\n Some(pos + offsets)\n .filter: nextPos =>\n topo.inBounds(nextPos) && topo(nextPos) == topo(pos) + 1\n topo.positions\n .map(pos => pos -> reachableNeighbors(pos))\n .toMap\n")),(0,n.kt)("p",null,"with this graph structure in hand, we can forget about the grid\nand solve the problem at a higher level of abstraction."),(0,n.kt)("h3",{id:"part-1"},"Part 1"),(0,n.kt)("p",null,"Part 1 is actually more difficult than part 2, in my opinion. In\nfact, in my first attempt to solve part 1, I accidentally solved part\n2! Once I saw part 2, I had to go back and reconstruct what I had done\nearlier."),(0,n.kt)("p",null,"From a given trailhead, the same summit may be reachable by multiple\nroutes. Therefore, we can't just count routes; we must remember what\nthe destinations are. Hence, the type of the recursive method is\n",(0,n.kt)("inlineCode",{parentName:"p"},"Set[Pos]")," -- the set of summits that are reachable from the current\nposition."),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-scala"}," def solve1(topo: Topo): Int =\n val graph = computeGraph(topo)\n def reachableSummits(pos: Pos): Set[Pos] =\n if topo(pos) == 9\n then Set(pos)\n else graph(pos).flatMap(reachableSummits)\n topo.positions\n .filter(pos => topo(pos) == 0)\n .map(pos => reachableSummits(pos).size)\n .sum\n\n def part1(name: String): Int =\n solve1(getInput(name))\n")),(0,n.kt)("p",null,"As mentioned earlier, note that we don't bother memoizing. That means\nwe're doing some redundant computation (when paths branch and then\nrejoin), but the code runs plenty fast anyway on the size of input\nthat we have."),(0,n.kt)("h3",{id:"part-2"},"Part 2"),(0,n.kt)("p",null,"The code for part 2 is nearly identical. We no longer need to de-duplicate\nroutes that have the same destination, so it's now sufficient for the recursion\nto return ",(0,n.kt)("inlineCode",{parentName:"p"},"Int"),"."),(0,n.kt)("p",null,"It would certainly be possible to refactor this to share more code\nwith part 1, but I've chosen to leave it this way."),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-scala"}," def solve2(topo: Topo): Int =\n val graph = computeGraph(topo)\n def routes(pos: Pos): Int =\n if topo(pos) == 9\n then 1\n else graph(pos).toSeq.map(routes).sum\n topo.positions\n .filter(pos => topo(pos) == 0)\n .map(routes)\n .sum\n\n def part2(name: String): Int =\n solve2(getInput(name))\n")),(0,n.kt)("p",null,"One tricky bit here is the necessity to include ",(0,n.kt)("inlineCode",{parentName:"p"},"toSeq")," when\nrecursing. That's because we have a ",(0,n.kt)("inlineCode",{parentName:"p"},"Set[Pos]"),", but if we ",(0,n.kt)("inlineCode",{parentName:"p"},".map(...)"),"\non a ",(0,n.kt)("inlineCode",{parentName:"p"},"Set"),", the result will also be a ",(0,n.kt)("inlineCode",{parentName:"p"},"Set"),". But we don't want to\nthrow away duplicate counts."),(0,n.kt)("h2",{id:"solutions-from-the-community"},"Solutions from the community"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/nikiforo/aoc24/blob/main/src/main/scala/io/github/nikiforo/aoc24/D10T2.scala"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/nikiforo"},"Artem Nikiforov")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/spamegg1/aoc/blob/master/2024/10/10.worksheet.sc#L166"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/spamegg1"},"Spamegg")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/samuelchassot/AdventCode_2024/blob/8cc89587c8558c7f55e2e0a3d6868290f0c5a739/10/Day10.scala"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/samuelchassot"},"Samuel Chassot")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/rmarbeck/advent2024/blob/main/day10/src/main/scala/Solution.scala"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/rmarbeck"},"Rapha\xebl Marbeck")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/nichobi/advent-of-code-2024/blob/main/10/solution.scala"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/nichobi"},"nichobi")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/rolandtritsch/scala3-aoc-2024/blob/trunk/src/aoc2024/Day10.scala"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/rolandtritsch"},"Roland Tritsch")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/makingthematrix/AdventOfCode2024/blob/main/src/main/scala/io/github/makingthematrix/AdventofCode2024/DayTen.scala"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/makingthematrix"},"Maciej Gorywoda")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/jnclt/adventofcode2024/blob/main/day10/hoof-it.sc"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/jnclt"},"jnclt")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/aamiguet/advent-2024/blob/main/src/main/scala/ch/aamiguet/advent2024/Day10.scala"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/aamiguet"},"Antoine Amiguet"))),(0,n.kt)("p",null,"Share your solution to the Scala community by editing this page.\nYou can even write the whole article! ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/scalacenter/scala-advent-of-code/discussions/424"},"See here for the expected format")))}c.isMDXComponent=!0}}]); \ No newline at end of file +"use strict";(self.webpackChunkwebsite=self.webpackChunkwebsite||[]).push([[2999],{4410:(e,t,a)=>{a.r(t),a.d(t,{assets:()=>l,contentTitle:()=>s,default:()=>c,frontMatter:()=>i,metadata:()=>r,toc:()=>p});var o=a(7462),n=(a(7294),a(3905));a(6340);const i={},s="Day 10: Hoof It",r={unversionedId:"2024/puzzles/day10",id:"2024/puzzles/day10",title:"Day 10: Hoof It",description:"by @SethTisue",source:"@site/target/mdoc/2024/puzzles/day10.md",sourceDirName:"2024/puzzles",slug:"/2024/puzzles/day10",permalink:"/scala-advent-of-code/2024/puzzles/day10",draft:!1,editUrl:"https://github.com/scalacenter/scala-advent-of-code/edit/website/docs/2024/puzzles/day10.md",tags:[],version:"current",frontMatter:{},sidebar:"adventOfCodeSidebar",previous:{title:"Day 9: Disk Fragmenter",permalink:"/scala-advent-of-code/2024/puzzles/day09"},next:{title:"Day 11: Plutonian Pebbles",permalink:"/scala-advent-of-code/2024/puzzles/day11"}},l={},p=[{value:"Puzzle description",id:"puzzle-description",level:2},{value:"Summary",id:"summary",level:2},{value:"Shared code",id:"shared-code",level:3},{value:"Part 1",id:"part-1",level:3},{value:"Part 2",id:"part-2",level:3},{value:"Solutions from the community",id:"solutions-from-the-community",level:2}],h={toc:p};function c(e){let{components:t,...a}=e;return(0,n.kt)("wrapper",(0,o.Z)({},h,a,{components:t,mdxType:"MDXLayout"}),(0,n.kt)("h1",{id:"day-10-hoof-it"},"Day 10: Hoof It"),(0,n.kt)("p",null,"by ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/SethTisue"},"@SethTisue")),(0,n.kt)("h2",{id:"puzzle-description"},"Puzzle description"),(0,n.kt)("p",null,(0,n.kt)("a",{parentName:"p",href:"https://adventofcode.com/2024/day/10"},"https://adventofcode.com/2024/day/10")),(0,n.kt)("h2",{id:"summary"},"Summary"),(0,n.kt)("p",null,"Like many Advent of Code puzzles, this is a graph search problem.\nSuch problems are highly amenable to recursive solutions."),(0,n.kt)("p",null,"In large graphs, it may be necessary to memoize intermediate results\nin order to get good performance. But here, it turns out that the\ngraphs are small enough that recursion alone does the job just fine."),(0,n.kt)("h3",{id:"shared-code"},"Shared code"),(0,n.kt)("p",null,"Let's start by representing coordinate pairs:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-scala"}," type Pos = (Int, Int)\n extension (pos: Pos)\n def +(other: Pos): Pos =\n (pos(0) + other(0), pos(1) + other(1))\n")),(0,n.kt)("p",null,"and the input grid:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-scala"}," type Topo = Vector[Vector[Int]]\n extension (topo: Topo)\n def apply(pos: Pos): Int =\n topo(pos(0))(pos(1))\n def inBounds(pos: Pos): Boolean =\n pos(0) >= 0 && pos(0) < topo.size &&\n pos(1) >= 0 && pos(1) < topo.head.size\n def positions =\n for row <- topo.indices\n column <- topo.head.indices\n yield (row, column)\n")),(0,n.kt)("p",null,"So far this is all quite typical code that is usable in many\nAdvent of Code puzzles."),(0,n.kt)("p",null,"Reading the input is typical as well:"),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-scala"}," def getInput(name: String): Topo =\n io.Source.fromResource(name)\n .getLines\n .map(_.map(_.asDigit).toVector)\n .toVector\n")),(0,n.kt)("p",null,'In order to avoid doing coordinate math all the time, let\'s turn the\ngrid into a graph by analyzing which cells are actually connected to\neach other. Each cell can only have a small number of "reachable"\nneighbors -- those neighbors that are exactly 1 higher than us.'),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-scala"}," type Graph = Map[Pos, Set[Pos]]\n\n def computeGraph(topo: Topo): Graph =\n def reachableNeighbors(pos: Pos): Set[Pos] =\n Set((-1, 0), (1, 0), (0, -1), (0, 1))\n .flatMap: offsets =>\n Some(pos + offsets)\n .filter: nextPos =>\n topo.inBounds(nextPos) && topo(nextPos) == topo(pos) + 1\n topo.positions\n .map(pos => pos -> reachableNeighbors(pos))\n .toMap\n")),(0,n.kt)("p",null,"with this graph structure in hand, we can forget about the grid\nand solve the problem at a higher level of abstraction."),(0,n.kt)("h3",{id:"part-1"},"Part 1"),(0,n.kt)("p",null,"Part 1 is actually more difficult than part 2, in my opinion. In\nfact, in my first attempt to solve part 1, I accidentally solved part\n2! Once I saw part 2, I had to go back and reconstruct what I had done\nearlier."),(0,n.kt)("p",null,"From a given trailhead, the same summit may be reachable by multiple\nroutes. Therefore, we can't just count routes; we must remember what\nthe destinations are. Hence, the type of the recursive method is\n",(0,n.kt)("inlineCode",{parentName:"p"},"Set[Pos]")," -- the set of summits that are reachable from the current\nposition."),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-scala"}," def solve1(topo: Topo): Int =\n val graph = computeGraph(topo)\n def reachableSummits(pos: Pos): Set[Pos] =\n if topo(pos) == 9\n then Set(pos)\n else graph(pos).flatMap(reachableSummits)\n topo.positions\n .filter(pos => topo(pos) == 0)\n .map(pos => reachableSummits(pos).size)\n .sum\n\n def part1(name: String): Int =\n solve1(getInput(name))\n")),(0,n.kt)("p",null,"As mentioned earlier, note that we don't bother memoizing. That means\nwe're doing some redundant computation (when paths branch and then\nrejoin), but the code runs plenty fast anyway on the size of input\nthat we have."),(0,n.kt)("h3",{id:"part-2"},"Part 2"),(0,n.kt)("p",null,"The code for part 2 is nearly identical. We no longer need to de-duplicate\nroutes that have the same destination, so it's now sufficient for the recursion\nto return ",(0,n.kt)("inlineCode",{parentName:"p"},"Int"),"."),(0,n.kt)("p",null,"It would certainly be possible to refactor this to share more code\nwith part 1, but I've chosen to leave it this way."),(0,n.kt)("pre",null,(0,n.kt)("code",{parentName:"pre",className:"language-scala"}," def solve2(topo: Topo): Int =\n val graph = computeGraph(topo)\n def routes(pos: Pos): Int =\n if topo(pos) == 9\n then 1\n else graph(pos).toSeq.map(routes).sum\n topo.positions\n .filter(pos => topo(pos) == 0)\n .map(routes)\n .sum\n\n def part2(name: String): Int =\n solve2(getInput(name))\n")),(0,n.kt)("p",null,"One tricky bit here is the necessity to include ",(0,n.kt)("inlineCode",{parentName:"p"},"toSeq")," when\nrecursing. That's because we have a ",(0,n.kt)("inlineCode",{parentName:"p"},"Set[Pos]"),", but if we ",(0,n.kt)("inlineCode",{parentName:"p"},".map(...)"),"\non a ",(0,n.kt)("inlineCode",{parentName:"p"},"Set"),", the result will also be a ",(0,n.kt)("inlineCode",{parentName:"p"},"Set"),". But we don't want to\nthrow away duplicate counts."),(0,n.kt)("h2",{id:"solutions-from-the-community"},"Solutions from the community"),(0,n.kt)("ul",null,(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/nikiforo/aoc24/blob/main/src/main/scala/io/github/nikiforo/aoc24/D10T2.scala"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/nikiforo"},"Artem Nikiforov")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/spamegg1/aoc/blob/master/2024/10/10.worksheet.sc#L166"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/spamegg1"},"Spamegg")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/samuelchassot/AdventCode_2024/blob/8cc89587c8558c7f55e2e0a3d6868290f0c5a739/10/Day10.scala"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/samuelchassot"},"Samuel Chassot")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/rmarbeck/advent2024/blob/main/day10/src/main/scala/Solution.scala"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/rmarbeck"},"Rapha\xebl Marbeck")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/nichobi/advent-of-code-2024/blob/main/10/solution.scala"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/nichobi"},"nichobi")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/rolandtritsch/scala3-aoc-2024/blob/trunk/src/aoc2024/Day10.scala"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/rolandtritsch"},"Roland Tritsch")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/makingthematrix/AdventOfCode2024/blob/main/src/main/scala/io/github/makingthematrix/AdventofCode2024/DayTen.scala"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/makingthematrix"},"Maciej Gorywoda")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/jnclt/adventofcode2024/blob/main/day10/hoof-it.sc"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/jnclt"},"jnclt")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/aamiguet/advent-2024/blob/main/src/main/scala/ch/aamiguet/advent2024/Day10.scala"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/aamiguet"},"Antoine Amiguet")),(0,n.kt)("li",{parentName:"ul"},(0,n.kt)("a",{parentName:"li",href:"https://github.com/scarf005/aoc-scala/blob/main/2024/day10.scala"},"Solution")," by ",(0,n.kt)("a",{parentName:"li",href:"https://github.com/scarf005"},"scarf"))),(0,n.kt)("p",null,"Share your solution to the Scala community by editing this page.\nYou can even write the whole article! ",(0,n.kt)("a",{parentName:"p",href:"https://github.com/scalacenter/scala-advent-of-code/discussions/424"},"See here for the expected format")))}c.isMDXComponent=!0}}]); \ No newline at end of file diff --git a/assets/js/runtime~main.9d085ce3.js b/assets/js/runtime~main.c59d6dd7.js similarity index 98% rename from assets/js/runtime~main.9d085ce3.js rename to assets/js/runtime~main.c59d6dd7.js index 4e70dc73a..35c3534a0 100644 --- a/assets/js/runtime~main.9d085ce3.js +++ b/assets/js/runtime~main.c59d6dd7.js @@ -1 +1 @@ -(()=>{"use strict";var e,f,a,c,d,b={},t={};function r(e){var f=t[e];if(void 0!==f)return f.exports;var a=t[e]={exports:{}};return b[e].call(a.exports,a,a.exports,r),a.exports}r.m=b,e=[],r.O=(f,a,c,d)=>{if(!a){var b=1/0;for(i=0;i=d)&&Object.keys(r.O).every((e=>r.O[e](a[o])))?a.splice(o--,1):(t=!1,d0&&e[i-1][2]>d;i--)e[i]=e[i-1];e[i]=[a,c,d]},r.n=e=>{var f=e&&e.__esModule?()=>e.default:()=>e;return r.d(f,{a:f}),f},a=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,r.t=function(e,c){if(1&c&&(e=this(e)),8&c)return e;if("object"==typeof e&&e){if(4&c&&e.__esModule)return e;if(16&c&&"function"==typeof e.then)return e}var d=Object.create(null);r.r(d);var b={};f=f||[null,a({}),a([]),a(a)];for(var t=2&c&&e;"object"==typeof t&&!~f.indexOf(t);t=a(t))Object.getOwnPropertyNames(t).forEach((f=>b[f]=()=>e[f]));return b.default=()=>e,r.d(d,b),d},r.d=(e,f)=>{for(var a in f)r.o(f,a)&&!r.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:f[a]})},r.f={},r.e=e=>Promise.all(Object.keys(r.f).reduce(((f,a)=>(r.f[a](e,f),f)),[])),r.u=e=>"assets/js/"+({1:"06fa13a8",53:"935f2afb",197:"f5cc1f00",341:"62432f74",578:"4cf3b8de",738:"e2b8a71b",771:"ba72e685",912:"d22639e6",968:"fbe461f6",1020:"4f7f4db9",1022:"bd8a6e4f",1078:"ff5f3c5c",1220:"de026f3e",1295:"a7c819ed",1377:"826e4024",1602:"eb8b4f18",1655:"3f15e8e2",1866:"ef006d58",1935:"89cb3c3f",2014:"d5cd8a03",2255:"a6e610da",2288:"e0cc4b4f",2402:"5a9b63f1",2678:"8ebe7983",2784:"9d8df37e",2863:"2e8f18da",2888:"4496c5bc",2953:"1d157876",2967:"559dca7a",2999:"b84e93db",3047:"a746aacc",3116:"f38a41fc",3159:"0a673ff4",3240:"950c6b93",3298:"4e95716f",3360:"e7ad7ee9",3414:"4fe84b5f",3760:"8790bf4c",3856:"1bbb7d86",3866:"bd59612b",4052:"73b9919f",4104:"a1a15f20",4120:"f4f7cb3a",4159:"738d623f",4195:"c4f5d8e4",4204:"18ed2f59",4404:"53a8669b",4459:"fe0d56d5",4480:"1d39ce0c",4608:"63121b24",4760:"0f5219f4",4871:"003324e5",4949:"dcec897c",5002:"1077c9b3",5099:"66145d18",5481:"212d8bd4",5511:"b0cdce56",5557:"4337dc21",5692:"3c0fac00",5934:"91df6ac7",6030:"1d58c4bc",6091:"fe537a1c",6279:"63b7595f",6324:"338c8fb2",6523:"d83a7229",6535:"23e93687",6538:"f03f5f80",6543:"63e9be74",6712:"95444edb",6754:"1d76bc70",6801:"1e184e91",7010:"5d7c1fea",7111:"1279ac73",7238:"94550ecd",7333:"cf8e1c86",7399:"507065a6",7508:"7c5e7584",7522:"6c07b263",7546:"18e96609",7589:"a66862ae",7684:"6cdb47d2",7784:"dd8a65aa",7918:"17896441",8119:"adcb9b5c",8158:"a9de53fa",8243:"ae238375",8592:"common",8752:"23b96a74",8801:"3cbbe704",8815:"33dcef45",8960:"c702c251",8998:"7db7ff8c",9010:"18dca702",9138:"ba4125a6",9185:"b468346a",9465:"808dec60",9468:"9f228057",9514:"1be78505",9898:"2301f76b",9965:"f89f89b6"}[e]||e)+"."+{1:"e2956b4b",53:"02db1b97",197:"fcda99f2",341:"3ca55eb2",578:"78872787",738:"7aaaa9a7",771:"94649af8",912:"25dc4a14",968:"954683c6",1020:"dd97aa7f",1022:"534d14d4",1078:"f8f3b41f",1220:"09b77bc5",1295:"68e5580a",1377:"1f374a78",1602:"bd62136d",1655:"f88dc56a",1866:"056c7a00",1935:"20272596",2014:"743bde90",2255:"66ab9f55",2288:"0b97b76a",2402:"f7547e19",2678:"d3a8d641",2784:"6f428408",2863:"a69f3cab",2888:"20bd6b65",2953:"340afdc5",2967:"9e82aea0",2999:"16b2ef16",3047:"4e94e74e",3116:"cfd43a11",3159:"89ccec3b",3240:"8dcb6957",3298:"76392a24",3360:"a717b9ea",3414:"1a0b007f",3760:"cf736643",3856:"8319d198",3866:"16dce187",4052:"fc88d6a4",4104:"5d2da92b",4120:"4b7046cc",4159:"6de87c9a",4195:"c77ef227",4204:"8e676de9",4404:"c75be289",4459:"d3758dfa",4480:"3d2c343f",4608:"47fc995c",4760:"d6578bb8",4871:"8acc9330",4949:"cb2eec7a",4972:"57117b7b",5002:"26f896c3",5099:"3cbd6c4c",5481:"d0d8890a",5511:"e6cf85dc",5557:"228fded2",5692:"606bafe1",5934:"463aad4d",6030:"25f10a3d",6091:"ea7491a5",6279:"59007993",6324:"b51cb585",6523:"154daaa8",6535:"e4513d16",6538:"3319aa0c",6543:"a09a5223",6712:"83d0923c",6754:"e0221e2b",6801:"519c3ceb",7010:"6eb40f33",7111:"8e356698",7238:"cc720fe6",7333:"ec915b68",7399:"a1782842",7508:"9472e4da",7522:"850ccd5e",7546:"58de9254",7589:"b80ccb53",7684:"46aae4fb",7784:"86c8e639",7918:"0df78363",8119:"6f65e5b3",8158:"66081784",8243:"a4f93248",8592:"41a1f24f",8752:"c240f78f",8801:"31202e80",8815:"65c82bef",8960:"0c5927db",8998:"09d447c9",9010:"65a45bb5",9138:"db8c06cd",9185:"71eb8acd",9465:"9e2480d3",9468:"2b879319",9514:"0cc6328f",9898:"b58da2ed",9965:"3ace8f5b"}[e]+".js",r.miniCssF=e=>{},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,f)=>Object.prototype.hasOwnProperty.call(e,f),c={},d="website:",r.l=(e,f,a,b)=>{if(c[e])c[e].push(f);else{var t,o;if(void 0!==a)for(var n=document.getElementsByTagName("script"),i=0;i{t.onerror=t.onload=null,clearTimeout(s);var d=c[e];if(delete c[e],t.parentNode&&t.parentNode.removeChild(t),d&&d.forEach((e=>e(a))),f)return f(a)},s=setTimeout(l.bind(null,void 0,{type:"timeout",target:t}),12e4);t.onerror=l.bind(null,t.onerror),t.onload=l.bind(null,t.onload),o&&document.head.appendChild(t)}},r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.p="/scala-advent-of-code/",r.gca=function(e){return e={17896441:"7918","06fa13a8":"1","935f2afb":"53",f5cc1f00:"197","62432f74":"341","4cf3b8de":"578",e2b8a71b:"738",ba72e685:"771",d22639e6:"912",fbe461f6:"968","4f7f4db9":"1020",bd8a6e4f:"1022",ff5f3c5c:"1078",de026f3e:"1220",a7c819ed:"1295","826e4024":"1377",eb8b4f18:"1602","3f15e8e2":"1655",ef006d58:"1866","89cb3c3f":"1935",d5cd8a03:"2014",a6e610da:"2255",e0cc4b4f:"2288","5a9b63f1":"2402","8ebe7983":"2678","9d8df37e":"2784","2e8f18da":"2863","4496c5bc":"2888","1d157876":"2953","559dca7a":"2967",b84e93db:"2999",a746aacc:"3047",f38a41fc:"3116","0a673ff4":"3159","950c6b93":"3240","4e95716f":"3298",e7ad7ee9:"3360","4fe84b5f":"3414","8790bf4c":"3760","1bbb7d86":"3856",bd59612b:"3866","73b9919f":"4052",a1a15f20:"4104",f4f7cb3a:"4120","738d623f":"4159",c4f5d8e4:"4195","18ed2f59":"4204","53a8669b":"4404",fe0d56d5:"4459","1d39ce0c":"4480","63121b24":"4608","0f5219f4":"4760","003324e5":"4871",dcec897c:"4949","1077c9b3":"5002","66145d18":"5099","212d8bd4":"5481",b0cdce56:"5511","4337dc21":"5557","3c0fac00":"5692","91df6ac7":"5934","1d58c4bc":"6030",fe537a1c:"6091","63b7595f":"6279","338c8fb2":"6324",d83a7229:"6523","23e93687":"6535",f03f5f80:"6538","63e9be74":"6543","95444edb":"6712","1d76bc70":"6754","1e184e91":"6801","5d7c1fea":"7010","1279ac73":"7111","94550ecd":"7238",cf8e1c86:"7333","507065a6":"7399","7c5e7584":"7508","6c07b263":"7522","18e96609":"7546",a66862ae:"7589","6cdb47d2":"7684",dd8a65aa:"7784",adcb9b5c:"8119",a9de53fa:"8158",ae238375:"8243",common:"8592","23b96a74":"8752","3cbbe704":"8801","33dcef45":"8815",c702c251:"8960","7db7ff8c":"8998","18dca702":"9010",ba4125a6:"9138",b468346a:"9185","808dec60":"9465","9f228057":"9468","1be78505":"9514","2301f76b":"9898",f89f89b6:"9965"}[e]||e,r.p+r.u(e)},(()=>{var e={1303:0,532:0};r.f.j=(f,a)=>{var c=r.o(e,f)?e[f]:void 0;if(0!==c)if(c)a.push(c[2]);else if(/^(1303|532)$/.test(f))e[f]=0;else{var d=new Promise(((a,d)=>c=e[f]=[a,d]));a.push(c[2]=d);var b=r.p+r.u(f),t=new Error;r.l(b,(a=>{if(r.o(e,f)&&(0!==(c=e[f])&&(e[f]=void 0),c)){var d=a&&("load"===a.type?"missing":a.type),b=a&&a.target&&a.target.src;t.message="Loading chunk "+f+" failed.\n("+d+": "+b+")",t.name="ChunkLoadError",t.type=d,t.request=b,c[1](t)}}),"chunk-"+f,f)}},r.O.j=f=>0===e[f];var f=(f,a)=>{var c,d,b=a[0],t=a[1],o=a[2],n=0;if(b.some((f=>0!==e[f]))){for(c in t)r.o(t,c)&&(r.m[c]=t[c]);if(o)var i=o(r)}for(f&&f(a);n{"use strict";var e,f,a,c,d,b={},t={};function r(e){var f=t[e];if(void 0!==f)return f.exports;var a=t[e]={exports:{}};return b[e].call(a.exports,a,a.exports,r),a.exports}r.m=b,e=[],r.O=(f,a,c,d)=>{if(!a){var b=1/0;for(i=0;i=d)&&Object.keys(r.O).every((e=>r.O[e](a[o])))?a.splice(o--,1):(t=!1,d0&&e[i-1][2]>d;i--)e[i]=e[i-1];e[i]=[a,c,d]},r.n=e=>{var f=e&&e.__esModule?()=>e.default:()=>e;return r.d(f,{a:f}),f},a=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,r.t=function(e,c){if(1&c&&(e=this(e)),8&c)return e;if("object"==typeof e&&e){if(4&c&&e.__esModule)return e;if(16&c&&"function"==typeof e.then)return e}var d=Object.create(null);r.r(d);var b={};f=f||[null,a({}),a([]),a(a)];for(var t=2&c&&e;"object"==typeof t&&!~f.indexOf(t);t=a(t))Object.getOwnPropertyNames(t).forEach((f=>b[f]=()=>e[f]));return b.default=()=>e,r.d(d,b),d},r.d=(e,f)=>{for(var a in f)r.o(f,a)&&!r.o(e,a)&&Object.defineProperty(e,a,{enumerable:!0,get:f[a]})},r.f={},r.e=e=>Promise.all(Object.keys(r.f).reduce(((f,a)=>(r.f[a](e,f),f)),[])),r.u=e=>"assets/js/"+({1:"06fa13a8",53:"935f2afb",197:"f5cc1f00",341:"62432f74",578:"4cf3b8de",738:"e2b8a71b",771:"ba72e685",912:"d22639e6",968:"fbe461f6",1020:"4f7f4db9",1022:"bd8a6e4f",1078:"ff5f3c5c",1220:"de026f3e",1295:"a7c819ed",1377:"826e4024",1602:"eb8b4f18",1655:"3f15e8e2",1866:"ef006d58",1935:"89cb3c3f",2014:"d5cd8a03",2255:"a6e610da",2288:"e0cc4b4f",2402:"5a9b63f1",2678:"8ebe7983",2784:"9d8df37e",2863:"2e8f18da",2888:"4496c5bc",2953:"1d157876",2967:"559dca7a",2999:"b84e93db",3047:"a746aacc",3116:"f38a41fc",3159:"0a673ff4",3240:"950c6b93",3298:"4e95716f",3360:"e7ad7ee9",3414:"4fe84b5f",3760:"8790bf4c",3856:"1bbb7d86",3866:"bd59612b",4052:"73b9919f",4104:"a1a15f20",4120:"f4f7cb3a",4159:"738d623f",4195:"c4f5d8e4",4204:"18ed2f59",4404:"53a8669b",4459:"fe0d56d5",4480:"1d39ce0c",4608:"63121b24",4760:"0f5219f4",4871:"003324e5",4949:"dcec897c",5002:"1077c9b3",5099:"66145d18",5481:"212d8bd4",5511:"b0cdce56",5557:"4337dc21",5692:"3c0fac00",5934:"91df6ac7",6030:"1d58c4bc",6091:"fe537a1c",6279:"63b7595f",6324:"338c8fb2",6523:"d83a7229",6535:"23e93687",6538:"f03f5f80",6543:"63e9be74",6712:"95444edb",6754:"1d76bc70",6801:"1e184e91",7010:"5d7c1fea",7111:"1279ac73",7238:"94550ecd",7333:"cf8e1c86",7399:"507065a6",7508:"7c5e7584",7522:"6c07b263",7546:"18e96609",7589:"a66862ae",7684:"6cdb47d2",7784:"dd8a65aa",7918:"17896441",8119:"adcb9b5c",8158:"a9de53fa",8243:"ae238375",8592:"common",8752:"23b96a74",8801:"3cbbe704",8815:"33dcef45",8960:"c702c251",8998:"7db7ff8c",9010:"18dca702",9138:"ba4125a6",9185:"b468346a",9465:"808dec60",9468:"9f228057",9514:"1be78505",9898:"2301f76b",9965:"f89f89b6"}[e]||e)+"."+{1:"e2956b4b",53:"02db1b97",197:"fcda99f2",341:"3ca55eb2",578:"78872787",738:"7aaaa9a7",771:"94649af8",912:"25dc4a14",968:"954683c6",1020:"dd97aa7f",1022:"534d14d4",1078:"f8f3b41f",1220:"09b77bc5",1295:"68e5580a",1377:"1f374a78",1602:"bd62136d",1655:"f88dc56a",1866:"056c7a00",1935:"20272596",2014:"743bde90",2255:"66ab9f55",2288:"0b97b76a",2402:"f7547e19",2678:"d3a8d641",2784:"6f428408",2863:"a69f3cab",2888:"20bd6b65",2953:"340afdc5",2967:"9e82aea0",2999:"a14062b6",3047:"4e94e74e",3116:"cfd43a11",3159:"89ccec3b",3240:"8dcb6957",3298:"76392a24",3360:"a717b9ea",3414:"1a0b007f",3760:"cf736643",3856:"8319d198",3866:"16dce187",4052:"fc88d6a4",4104:"c7225a78",4120:"4b7046cc",4159:"6de87c9a",4195:"c77ef227",4204:"8e676de9",4404:"c75be289",4459:"d3758dfa",4480:"3d2c343f",4608:"47fc995c",4760:"d6578bb8",4871:"8acc9330",4949:"cb2eec7a",4972:"57117b7b",5002:"26f896c3",5099:"3cbd6c4c",5481:"d0d8890a",5511:"e6cf85dc",5557:"228fded2",5692:"606bafe1",5934:"463aad4d",6030:"25f10a3d",6091:"ea7491a5",6279:"59007993",6324:"b51cb585",6523:"154daaa8",6535:"e4513d16",6538:"3319aa0c",6543:"a09a5223",6712:"83d0923c",6754:"e0221e2b",6801:"519c3ceb",7010:"6eb40f33",7111:"8e356698",7238:"cc720fe6",7333:"ec915b68",7399:"a1782842",7508:"9472e4da",7522:"850ccd5e",7546:"58de9254",7589:"b80ccb53",7684:"46aae4fb",7784:"86c8e639",7918:"0df78363",8119:"6f65e5b3",8158:"66081784",8243:"a4f93248",8592:"41a1f24f",8752:"c240f78f",8801:"31202e80",8815:"65c82bef",8960:"0c5927db",8998:"09d447c9",9010:"65a45bb5",9138:"db8c06cd",9185:"71eb8acd",9465:"9e2480d3",9468:"2b879319",9514:"0cc6328f",9898:"b58da2ed",9965:"3ace8f5b"}[e]+".js",r.miniCssF=e=>{},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,f)=>Object.prototype.hasOwnProperty.call(e,f),c={},d="website:",r.l=(e,f,a,b)=>{if(c[e])c[e].push(f);else{var t,o;if(void 0!==a)for(var n=document.getElementsByTagName("script"),i=0;i{t.onerror=t.onload=null,clearTimeout(s);var d=c[e];if(delete c[e],t.parentNode&&t.parentNode.removeChild(t),d&&d.forEach((e=>e(a))),f)return f(a)},s=setTimeout(l.bind(null,void 0,{type:"timeout",target:t}),12e4);t.onerror=l.bind(null,t.onerror),t.onload=l.bind(null,t.onload),o&&document.head.appendChild(t)}},r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.p="/scala-advent-of-code/",r.gca=function(e){return e={17896441:"7918","06fa13a8":"1","935f2afb":"53",f5cc1f00:"197","62432f74":"341","4cf3b8de":"578",e2b8a71b:"738",ba72e685:"771",d22639e6:"912",fbe461f6:"968","4f7f4db9":"1020",bd8a6e4f:"1022",ff5f3c5c:"1078",de026f3e:"1220",a7c819ed:"1295","826e4024":"1377",eb8b4f18:"1602","3f15e8e2":"1655",ef006d58:"1866","89cb3c3f":"1935",d5cd8a03:"2014",a6e610da:"2255",e0cc4b4f:"2288","5a9b63f1":"2402","8ebe7983":"2678","9d8df37e":"2784","2e8f18da":"2863","4496c5bc":"2888","1d157876":"2953","559dca7a":"2967",b84e93db:"2999",a746aacc:"3047",f38a41fc:"3116","0a673ff4":"3159","950c6b93":"3240","4e95716f":"3298",e7ad7ee9:"3360","4fe84b5f":"3414","8790bf4c":"3760","1bbb7d86":"3856",bd59612b:"3866","73b9919f":"4052",a1a15f20:"4104",f4f7cb3a:"4120","738d623f":"4159",c4f5d8e4:"4195","18ed2f59":"4204","53a8669b":"4404",fe0d56d5:"4459","1d39ce0c":"4480","63121b24":"4608","0f5219f4":"4760","003324e5":"4871",dcec897c:"4949","1077c9b3":"5002","66145d18":"5099","212d8bd4":"5481",b0cdce56:"5511","4337dc21":"5557","3c0fac00":"5692","91df6ac7":"5934","1d58c4bc":"6030",fe537a1c:"6091","63b7595f":"6279","338c8fb2":"6324",d83a7229:"6523","23e93687":"6535",f03f5f80:"6538","63e9be74":"6543","95444edb":"6712","1d76bc70":"6754","1e184e91":"6801","5d7c1fea":"7010","1279ac73":"7111","94550ecd":"7238",cf8e1c86:"7333","507065a6":"7399","7c5e7584":"7508","6c07b263":"7522","18e96609":"7546",a66862ae:"7589","6cdb47d2":"7684",dd8a65aa:"7784",adcb9b5c:"8119",a9de53fa:"8158",ae238375:"8243",common:"8592","23b96a74":"8752","3cbbe704":"8801","33dcef45":"8815",c702c251:"8960","7db7ff8c":"8998","18dca702":"9010",ba4125a6:"9138",b468346a:"9185","808dec60":"9465","9f228057":"9468","1be78505":"9514","2301f76b":"9898",f89f89b6:"9965"}[e]||e,r.p+r.u(e)},(()=>{var e={1303:0,532:0};r.f.j=(f,a)=>{var c=r.o(e,f)?e[f]:void 0;if(0!==c)if(c)a.push(c[2]);else if(/^(1303|532)$/.test(f))e[f]=0;else{var d=new Promise(((a,d)=>c=e[f]=[a,d]));a.push(c[2]=d);var b=r.p+r.u(f),t=new Error;r.l(b,(a=>{if(r.o(e,f)&&(0!==(c=e[f])&&(e[f]=void 0),c)){var d=a&&("load"===a.type?"missing":a.type),b=a&&a.target&&a.target.src;t.message="Loading chunk "+f+" failed.\n("+d+": "+b+")",t.name="ChunkLoadError",t.type=d,t.request=b,c[1](t)}}),"chunk-"+f,f)}},r.O.j=f=>0===e[f];var f=(f,a)=>{var c,d,b=a[0],t=a[1],o=a[2],n=0;if(b.some((f=>0!==e[f]))){for(c in t)r.o(t,c)&&(r.m[c]=t[c]);if(o)var i=o(r)}for(f&&f(a);n Scala Center Advent of Code | Scala Center Advent of Code - + - + \ No newline at end of file diff --git a/introduction/index.html b/introduction/index.html index 8152d3aaa..b618c7ba7 100644 --- a/introduction/index.html +++ b/introduction/index.html @@ -5,7 +5,7 @@ Introduction | Scala Center Advent of Code - + @@ -18,7 +18,7 @@ We will strive to only use the Scala standard library to solve the puzzles, so that no specific knowledge of external libraries is necessary to follow along.

    Participate

    In addition, if you have your own solution for a puzzle and would like to share it, you can add a link to a gist in the solution page of the puzzles.

    If you would like to discuss the puzzles with other developers, or discuss our solutions on the following day, drop by the the Scala Discord server, in the #advent-of-code channel. There you can also find a pinned message with the invite code for a private leaderboard including those from the Scala community for some friendly competition.

    Do you want to get your hands dirty and solve the Advent of Code puzzles in Scala? Read ahead to the Setup page!

    - + \ No newline at end of file diff --git a/puzzles/day1/index.html b/puzzles/day1/index.html index 948baa735..34503046f 100644 --- a/puzzles/day1/index.html +++ b/puzzles/day1/index.html @@ -5,7 +5,7 @@ Day 1: Sonar Sweep | Scala Center Advent of Code - + @@ -16,7 +16,7 @@ For example, the sliding window of size 3 of Seq(10, 20, 30, 40, 50) is:

    Seq(Seq(10, 20, 30), Seq(20, 30, 40), Seq(30, 40, 50)).

    We can generalize this procedure in a method that compute a sliding window of some size n on any sequence of elements. Such a method already exists in the Scala standard library under the name sliding. It returns an iterator of arrays.

    $ Seq(10, 20, 30, 40, 50).sliding(3).toSeq
    Seq(Array(10, 20, 30), Array(20, 30, 40), Array(30, 40, 50))

    We can use the sliding method to make our code shorter and faster.

    Final solution

    def part1(input: String): Int =
    val depths = input.linesIterator.map(_.toInt)
    val pairs = depths.sliding(2).map(arr => (arr(0), arr(1)))
    pairs.count((prev, next) => prev < next)

    def part2(input: String): Int =
    val depths = input.linesIterator.map(_.toInt)
    val sums = depths.sliding(3).map(_.sum)
    val pairs = sums.sliding(2).map(arr => (arr(0), arr(1)))
    pairs.count((prev, next) => prev < next)

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd scala-advent-of-code

    The you can run it with scala-cli:

    $ scala-cli 2021 -M day1.part1
    The answer is 1559

    $ scala-cli 2021 -M template1.part2
    The answer is 1600

    You can replace the content of the input/day1 file with your own input from adventofcode.com to get your own solution.

    Run it in the browser

    Part 1

    Part 2

    Bonus

    There is a trick to make the solution of part 2 even smaller.

    Indeed comparing depths(i) + depths(i + 1) + depths(i + 2) with depths(i + 1) + depths(i + 2) + depths(i + 3) is the same as comparing depths(i) with depths(i + 3). So the second part of the puzzle is almost the same as the first part of the puzzle.

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day10/index.html b/puzzles/day10/index.html index a70931db5..645fb0faa 100644 --- a/puzzles/day10/index.html +++ b/puzzles/day10/index.html @@ -5,7 +5,7 @@ Day 10: Syntax Scoring | Scala Center Advent of Code - + @@ -47,7 +47,7 @@ the element in the middle:

    def part2(input: String): BigInt =
    val rows: LazyList[List[Symbol]] =
    input.linesIterator
    .to(LazyList)
    .map(parseRow)

    val scores =
    rows.map(checkChunks)
    .collect { case incomplete: CheckResult.Incomplete => incomplete.score }
    .toVector
    .sorted

    scores(scores.length / 2)

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd scala-advent-of-code

    You can run it with scala-cli.

    $ scala-cli 2021 -M day10.part1
    The solution is 367059
    $ scala-cli 2021 -M day10.part2
    The solution is 1952146692

    You can replace the content of the input/day10 file with your own input from adventofcode.com to get your own solution.

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day11/index.html b/puzzles/day11/index.html index 247b59413..e8912910a 100644 --- a/puzzles/day11/index.html +++ b/puzzles/day11/index.html @@ -5,14 +5,14 @@ Day 11: Dumbo Octopus | Scala Center Advent of Code - +
    Skip to main content

    Day 11: Dumbo Octopus

    by @tgodzik

    Puzzle description

    https://adventofcode.com/2021/day/11

    Final Solution

    trait Step:
    def increment: Step
    def addFlashes(f: Int): Step
    def shouldStop: Boolean
    def currentFlashes: Int
    def stepNumber: Int

    case class MaxIterStep(currentFlashes: Int, stepNumber: Int, max: Int) extends Step:
    def increment = this.copy(stepNumber = stepNumber + 1)
    def addFlashes(f: Int) = this.copy(currentFlashes = currentFlashes + f)
    def shouldStop = stepNumber == max

    case class SynchronizationStep(
    currentFlashes: Int,
    stepNumber: Int,
    maxChange: Int,
    lastFlashes: Int
    ) extends Step:
    def increment = this.copy(stepNumber = stepNumber + 1)
    def addFlashes(f: Int) =
    this.copy(currentFlashes = currentFlashes + f, lastFlashes = currentFlashes)
    def shouldStop = currentFlashes - lastFlashes == maxChange

    case class Point(x: Int, y: Int)
    case class Octopei(inputMap: Map[Point, Int]):

    @tailrec
    private def propagate(
    toVisit: Queue[Point],
    alreadyFlashed: Set[Point],
    currentSituation: Map[Point, Int]
    ): Map[Point, Int] =
    toVisit.dequeueOption match
    case None => currentSituation
    case Some((point, dequeued)) =>
    currentSituation.get(point) match
    case Some(value) if value > 9 && !alreadyFlashed(point) =>
    val propagated =
    Seq(
    point.copy(x = point.x + 1),
    point.copy(x = point.x - 1),
    point.copy(y = point.y + 1),
    point.copy(y = point.y - 1),
    point.copy(x = point.x + 1, y = point.y + 1),
    point.copy(x = point.x + 1, y = point.y - 1),
    point.copy(x = point.x - 1, y = point.y + 1),
    point.copy(x = point.x - 1, y = point.y - 1)
    )
    val newSituation = propagated.foldLeft(currentSituation) {
    case (map, point) =>
    map.get(point) match
    case Some(value) => map.updated(point, value + 1)
    case _ => map
    }
    propagate(
    dequeued.appendedAll(propagated),
    alreadyFlashed + point,
    newSituation
    )
    case _ =>
    propagate(dequeued, alreadyFlashed, currentSituation)
    end propagate

    def simulate(step: Step) = simulateIter(step, inputMap)

    @tailrec
    private def simulateIter(
    step: Step,
    currentSituation: Map[Point, Int]
    ): Step =
    if step.shouldStop then step
    else
    val incremented = currentSituation.map { case (point, value) =>
    (point, value + 1)
    }
    val flashes = incremented.collect {
    case (point, value) if value > 9 => point
    }.toList
    val propagated = propagate(Queue(flashes*), Set.empty, incremented)
    val newFlashes = propagated.collect {
    case (point, value) if value > 9 => 1
    }.sum
    val zeroed = propagated.map {
    case (point, value) if value > 9 => (point, 0)
    case same => same
    }
    simulateIter(step.increment.addFlashes(newFlashes), zeroed)
    end simulateIter

    end Octopei

    def part1(input: String) =
    val octopei = parse(input)
    val step = MaxIterStep(0, 0, 100)
    octopei.simulate(step).currentFlashes

    def part2(input: String) =
    val octopei = parse(input)
    val step = SynchronizationStep(0, 0, octopei.inputMap.size, 0)
    octopei.simulate(step).stepNumber

    Run it in the browser

    Part 1

    Part 2

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd scala-advent-of-code

    You can run it with scala-cli.

    $ scala-cli 2021 -M day11.part1
    The answer is: 1673

    $ scala-cli 2021 -M day11.part2
    The answer is: 279

    You can replace the content of the input/day11 file with your own input from adventofcode.com to get your own solution.

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/puzzles/day12/index.html b/puzzles/day12/index.html index 5e660dba0..088ace70e 100644 --- a/puzzles/day12/index.html +++ b/puzzles/day12/index.html @@ -5,14 +5,14 @@ Day 12: Passage Pathing | Scala Center Advent of Code - +
    Skip to main content
    - + \ No newline at end of file diff --git a/puzzles/day13/index.html b/puzzles/day13/index.html index 799e3c9e0..bc5d34f9b 100644 --- a/puzzles/day13/index.html +++ b/puzzles/day13/index.html @@ -5,7 +5,7 @@ Day 13: Transparent Origami | Scala Center Advent of Code - + @@ -22,7 +22,7 @@ Finally we convert this double array to a String with .map(_.mkString).mkString('\n').

    def part2(input: String): String =
    val (dots, folds) = parseInstructions(input)
    val foldedDots = folds.foldLeft(dots)((dots, fold) => dots.map(fold.apply))

    val (width, height) = (foldedDots.map(_.x).max + 1, foldedDots.map(_.y).max + 1)
    val paper = Array.fill(height, width)('.')
    for dot <- foldedDots do paper(dot.y)(dot.x) = '#'

    paper.map(_.mkString).mkString("\n")

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd scala-advent-of-code

    You can run it with scala-cli.

    $ scala-cli 2021 -M day13.part1
    The answer is: 788

    $ scala-cli 2021 -M day10.part2
    The answer is:
    #..#...##.###..#..#.####.#..#.###...##.
    #.#.....#.#..#.#.#..#....#..#.#..#.#..#
    ##......#.###..##...###..#..#.###..#...
    #.#.....#.#..#.#.#..#....#..#.#..#.#.##
    #.#..#..#.#..#.#.#..#....#..#.#..#.#..#
    #..#..##..###..#..#.####..##..###...###

    You can replace the content of the input/day13 file with your own input from adventofcode.com to get your own solution.

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day14/index.html b/puzzles/day14/index.html index 0f1e44e80..a54d5805d 100644 --- a/puzzles/day14/index.html +++ b/puzzles/day14/index.html @@ -5,7 +5,7 @@ Day 14: Extended Polymerization | Scala Center Advent of Code - + @@ -25,7 +25,7 @@ We can use the sum of multisets, noted with ++ and Σ\Sigma, which accumulates counts.

    With the definitions above, we can proceed with solving our problem.

    For any string longer than 2 chars, we have the following property:

    S(x1x2x3xp,n)=Σi=1p1(S(xixi+1,n))S(x_1 x_2 x_3 \cdots x_p, n) = \Sigma_{i=1}^{p-1} (S(x_i x_{i+1}, n))

    In other words, SS for a string is the sum (a multiset sum) of SS for all the adjacent pairs in the string, with the same number of iterations nn. That is because each initial pair of letters (such as NN, NC and CB) expands independently of the others. Each initial char is counted exactly once in the final frequencies because it is counted as part of the expansion of the pair on its left, and not the expansion of the pair on its right (we always exclude the first char).

    As a particular case of the above, for a string of 3 chars xzyxzy, we have

    S(xzy,n)=S(xz,n)+S(zy,n)S(xzy, n) = S(xz, n) + S(zy, n)

    For strings of length 2, we have two cases: n=0n = 0 and n>0n > 0.

    Base case: a pair xyxy, and n=0n = 0

    S(xy,0)={y1} for all x,y (by definition)S(xy, 0) = \{ y \rightarrow 1 \} \text{ for all } x, y \text{ (by definition)}

    Inductive case: a pair xyxy, and n>0n > 0

    S(xy,n)=S(xzy,n1) where z is the insertion char for the pair xy (by definition)=S(xz,n1)+S(zy,n1) – the particular case of 3 chars above\begin{aligned} S(xy, n) & = S(xzy, n-1) \text{ where $z$ is the insertion char for the pair $xy$ (by definition)} \\ & = S(xz, n-1) + S(zy, n-1) \text{ -- the particular case of 3 chars above} \end{aligned}

    This means that the frequencies of letters after xyxy has produced its final polymer are equal to the sum of frequencies that xzyxzy produces after 1 fewer steps.

    Now that we have an inductive definition of S(xy,n)S(xy, n) for all pairs, we can write an iterative algorithm that computes that for all possible pairs xyxy, for n[0,40]n \in \lbrack 0, 40 \rbrack :

    // S : (charPair, n) -> frequencies
    val S = mutable.Map.empty[(CharPair, Int), Frequencies]

    // Base case: S(xy, 0) = {y -> 1} for all x, y
    for (pair @ (first, second), insert) <- insertionRules do
    S((pair, 0)) = Map(second -> 1L)

    // Recursive case S(xy, n) = S(xz, n - 1) + S(zy, n - 1) with z = insertionRules(xy)
    for n <- 1 to 40 do
    for (pair, insert) <- insertionRules do
    val (x, y) = pair
    val z = insertionRules(pair)
    S((pair, n)) = addFrequencies(S((x, z), n - 1), S((z, y), n - 1))

    where addFrequencies implements the multiset sum of two bags of frequencies:

    def addFrequencies(a: Frequencies, b: Frequencies): Frequencies =
    b.foldLeft(a) { case (prev, (char, frequency)) =>
    prev + (char -> (prev.getOrElse(char, 0L) + frequency))
    }

    Using the initial property of SS for strings longer than 2 chars, we can compute S(initialPolymer,40)S(\text{initialPolymer}, 40) from the compute S(xy,40)S(xy, 40):

    // S(polymer, 40) = ∑(S(pair, 40))
    val pairsInPolymer = initialPolymer.zip(initialPolymer.tail)
    val polymerS = (for pair <- pairsInPolymer yield S(pair, 40)).reduce(addFrequencies)

    And finally, we add the very first character, once, to compute the full frequencies:

    // We have to add the very first char to get all the frequencies
    val frequencies = addFrequencies(polymerS, Map(initialPolymer.head -> 1L))

    After which we have all the pieces for part 2.

    Final code for part 2

    def part2(input: String): Long =
    val (initialPolymer, insertionRules) = parseInput(input)

    // S : (charPair, n) -> frequencies of everything but the first char after n iterations from charPair
    val S = mutable.Map.empty[(CharPair, Int), Frequencies]

    // Base case: S(xy, 0) = {y -> 1} for all x, y
    for (pair @ (first, second), insert) <- insertionRules do
    S((pair, 0)) = Map(second -> 1L)

    // Recursive case S(xy, n) = S(xz, n - 1) + S(zy, n - 1) with z = insertionRules(xy)
    for n <- 1 to 40 do
    for (pair, insert) <- insertionRules do
    val (x, y) = pair
    val z = insertionRules(pair)
    S((pair, n)) = addFrequencies(S((x, z), n - 1), S((z, y), n - 1))

    // S(polymer, 40) = ∑(S(pair, 40))
    val pairsInPolymer = initialPolymer.zip(initialPolymer.tail)
    val polymerS = (for pair <- pairsInPolymer yield S(pair, 40)).reduce(addFrequencies)

    // We have to add the very first char to get all the frequencies
    val frequencies = addFrequencies(polymerS, Map(initialPolymer.head -> 1L))

    // Finally, we can finish the computation as in part 1
    val max = frequencies.values.max
    val min = frequencies.values.min
    max - min

    def addFrequencies(a: Frequencies, b: Frequencies): Frequencies =
    b.foldLeft(a) { case (prev, (char, frequency)) =>
    prev + (char -> (prev.getOrElse(char, 0L) + frequency))
    }

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd scala-advent-of-code

    You can run it with scala-cli.

    $ scala-cli 2021 -M day14.part1
    The answer is: 3306

    $ scala-cli 2021 -M day14.part2
    The answer is: 3760312702877

    You can replace the content of the input/day14 file with your own input from adventofcode.com to get your own solution.

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day15/index.html b/puzzles/day15/index.html index 926034a00..76bf5ced1 100644 --- a/puzzles/day15/index.html +++ b/puzzles/day15/index.html @@ -5,13 +5,13 @@ Day 15: Chiton | Scala Center Advent of Code - +
    Skip to main content

    Day 15: Chiton

    By @anatoliykmetyuk

    Puzzle description

    https://adventofcode.com/2021/day/15

    Problem

    The problem in its essence is that of finding the least-costly path through a graph. This problem is solved by Dijkstra's algorithm, nicely explained in this Computerphile video.

    Domain Model

    The two domain entities we are working with are the game map and an individual cell of that map. In presence of the game map, a cell is fully described by a pair of its coordinates.

    type Coord = (Int, Int)

    The game map contains all the cells from the challenge input. It also defines the neighbours of a given cell, which we need to know for Dijkstra's algorithm. Finally, it defines a function to get the cost of entering a given cell.

    class GameMap(cells: IndexedSeq[IndexedSeq[Int]]):
    val maxRow = cells.length - 1
    val maxCol = cells.head.length - 1

    def neighboursOf(c: Coord): List[Coord] =
    val (row, col) = c
    val lb = mutable.ListBuffer.empty[Coord]
    if row < maxRow then lb.append((row+1, col))
    if row > 0 then lb.append((row-1, col))
    if col < maxCol then lb.append((row, col+1))
    if col > 0 then lb.append((row, col-1))
    lb.toList

    def costOf(c: Coord): Int = c match
    case (row, col) => cells(row)(col)
    end GameMap

    IndexedSeq in the cells type is important for this algorithm since we are doing a lot of index-based accesses, so we need to use a data structure optimized for that.

    Algorithm – Part 1

    We start the solution by defining three data structures for the algorithm:

    val visited = mutable.Set.empty[Coord]
    val dist = mutable.Map[Coord, Int]((0, 0) -> 0)
    val queue = java.util.PriorityQueue[Coord](Ordering.by(dist))
    queue.add((0, 0))

    The first one is a Set of all visited nodes – the ones the algorithm will not look at again. The second one is a Map of distances containing the smallest currently known distance from the top-left corner of the map to the given cell. Finally, the third one is a java.util.PriorityQueue that defines in which order to examine cells. We are using Java's PriorityQueue, not the Scala's one since the Java PriorityQueue implementation defines the remove operation on the queue which is necessary for efficient implementation and which the Scala queue lacks.

    We also initialize the queue with the first node we are going to examine – the top-left corner of the map.

    Once we have the data structures, there's a loop which runs Dijkstra's algorithm on those structures:

    while queue.peek() != null do
    val c = queue.poll()
    visited += c
    val newNodes: List[Coord] = gameMap.neighboursOf(c).filterNot(visited)
    val cDist = dist(c)
    for n <- newNodes do
    val newDist = cDist + gameMap.costOf(n)
    if !dist.contains(n) || dist(n) > newDist then
    dist(n) = newDist
    queue.remove(n)
    queue.add(n)
    dist((gameMap.maxRow, gameMap.maxCol))

    We use queue.remove(n) followed by queue.add(n) here – this is to recompute the position of n in the queue following the change in the ordering of the queue (that is, the mutation of dist). Ideally, you would need a decreaseKey operation on the priority queue for the best performance – but that would require writing a dedicated data structure, which is out of scope for this solution.

    Part 2

    Part 2 is like Part 1 but 25 times larger. The Part 1 algorithm is capable of dealing with scale, and so the only challenge is to construct the game map for part 2.

    We generate the Part 2 game map from the Part 1 map using three nested loops:

    val seedTile = readInput()
    val gameMap = GameMap(
    (0 until 5).flatMap { tileIdVertical =>
    for row <- seedTile yield
    for
    tileIdHorizontal <- 0 until 5
    cell <- row
    yield (cell + tileIdHorizontal + tileIdVertical - 1) % 9 + 1
    }
    )

    The innermost loop generates individual cells according to the challenge spec. The second-level loop pads the 100x100 tiles of the map horizontally, starting from the seedTile (the one used in Part 1). Finally, the outermost loop pads the tiles vertically.

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day16/index.html b/puzzles/day16/index.html index 55ae15b5b..36be5f8de 100644 --- a/puzzles/day16/index.html +++ b/puzzles/day16/index.html @@ -5,7 +5,7 @@ Day 16: Packet Decoder | Scala Center Advent of Code - + @@ -54,7 +54,7 @@ that will calculate the equation. We can do it similarly to the versionsSum function in the previous part:

      def value: Long =
    this match
    case Sum(version, exprs) => exprs.map(_.value).sum
    case Product(version, exprs) => exprs.map(_.value).reduce(_ * _)
    case Minimum(version, exprs) => exprs.map(_.value).min
    case Maximum(version, exprs) => exprs.map(_.value).max
    case Literal(version, value) => value
    case GreaterThan(version, lhs, rhs) => if lhs.value > rhs.value then 1 else 0
    case LesserThan(version, lhs, rhs) => if lhs.value < rhs.value then 1 else 0
    case Equals(version, lhs, rhs) => if lhs.value == rhs.value then 1 else 0

    Full solution

    package day16

    import scala.util.Using
    import scala.io.Source
    import scala.annotation.tailrec

    @main def part1(): Unit =
    println(s"The solution is ${part1(readInput())}")

    @main def part2(): Unit =
    println(s"The solution is ${part2(readInput())}")

    def readInput(): String =
    Using.resource(Source.fromFile("input/day16"))(_.mkString)

    val hexadecimalMapping =
    Map(
    '0' -> "0000",
    '1' -> "0001",
    '2' -> "0010",
    '3' -> "0011",
    '4' -> "0100",
    '5' -> "0101",
    '6' -> "0110",
    '7' -> "0111",
    '8' -> "1000",
    '9' -> "1001",
    'A' -> "1010",
    'B' -> "1011",
    'C' -> "1100",
    'D' -> "1101",
    'E' -> "1110",
    'F' -> "1111"
    )

    /*
    * Structures for all possible operators
    */
    enum Packet(version: Int, typeId: Int):
    case Sum(version: Int, exprs: List[Packet]) extends Packet(version, 0)
    case Product(version: Int, exprs: List[Packet]) extends Packet(version, 1)
    case Minimum(version: Int, exprs: List[Packet]) extends Packet(version, 2)
    case Maximum(version: Int, exprs: List[Packet]) extends Packet(version, 3)
    case Literal(version: Int, literalValue: Long) extends Packet(version, 4)
    case GreaterThan(version: Int, lhs: Packet, rhs: Packet) extends Packet(version, 5)
    case LesserThan(version: Int, lhs: Packet, rhs: Packet) extends Packet(version, 6)
    case Equals(version: Int, lhs: Packet, rhs: Packet) extends Packet(version, 7)

    def versionSum: Int =
    this match
    case Sum(version, exprs) => version + exprs.map(_.versionSum).sum
    case Product(version, exprs) => version + exprs.map(_.versionSum).sum
    case Minimum(version, exprs) => version + exprs.map(_.versionSum).sum
    case Maximum(version, exprs) => version + exprs.map(_.versionSum).sum
    case Literal(version, value) => version
    case GreaterThan(version, lhs, rhs) => version + lhs.versionSum + rhs.versionSum
    case LesserThan(version, lhs, rhs) => version + lhs.versionSum + rhs.versionSum
    case Equals(version, lhs, rhs) => version + lhs.versionSum + rhs.versionSum

    def value: Long =
    this match
    case Sum(version, exprs) => exprs.map(_.value).sum
    case Product(version, exprs) => exprs.map(_.value).reduce(_ * _)
    case Minimum(version, exprs) => exprs.map(_.value).min
    case Maximum(version, exprs) => exprs.map(_.value).max
    case Literal(version, value) => value
    case GreaterThan(version, lhs, rhs) => if lhs.value > rhs.value then 1 else 0
    case LesserThan(version, lhs, rhs) => if lhs.value < rhs.value then 1 else 0
    case Equals(version, lhs, rhs) => if lhs.value == rhs.value then 1 else 0
    end Packet

    type BinaryData = List[Char]

    inline def toInt(chars: BinaryData): Int =
    Integer.parseInt(chars.mkString, 2)

    inline def toLong(chars: BinaryData): Long =
    java.lang.Long.parseLong(chars.mkString, 2)

    @tailrec
    def readLiteralBody(tail: BinaryData, numAcc: BinaryData): (Long, BinaryData) =
    val (num, rest) = tail.splitAt(5)
    if num(0) == '1' then readLiteralBody(rest, numAcc.appendedAll(num.drop(1)))
    else
    val bits = numAcc.appendedAll(num.drop(1))
    (toLong(bits), rest)
    end readLiteralBody

    def readOperatorBody(current: BinaryData): (List[Packet], BinaryData) =
    val (lenId, rest) = current.splitAt(1)

    @tailrec
    def readMaxBits(
    current: BinaryData,
    remaining: Int,
    acc: List[Packet]
    ): (List[Packet], BinaryData) =
    if remaining == 0 then (acc, current)
    else
    val (newExpr, rest) = decodePacket(current)
    readMaxBits(rest, remaining - (current.size - rest.size), acc :+ newExpr)

    @tailrec
    def readMaxPackets(
    current: BinaryData,
    remaining: Int,
    acc: List[Packet]
    ): (List[Packet], BinaryData) =
    if remaining == 0 then (acc, current)
    else
    val (newExpr, rest) = decodePacket(current)
    readMaxPackets(rest, remaining - 1, acc :+ newExpr)

    lenId match
    // read based on length
    case List('0') =>
    val (size, packets) = rest.splitAt(15)
    readMaxBits(packets, toInt(size), Nil)

    // read based on number of packages
    case _ =>
    val (size, packets) = rest.splitAt(11)
    readMaxPackets(packets, toInt(size), Nil)
    end match
    end readOperatorBody

    def decodePacket(packet: BinaryData): (Packet, BinaryData) =
    val (versionBits, rest) = packet.splitAt(3)
    val version = toInt(versionBits)
    val (typeBits, body) = rest.splitAt(3)
    val tpe = toInt(typeBits)

    tpe match
    case 4 =>
    val (value, remaining) = readLiteralBody(body, Nil)
    (Packet.Literal(version, value), remaining)
    case otherTpe =>
    val (values, remaining) = readOperatorBody(body)
    otherTpe match
    case 0 => (Packet.Sum(version, values), remaining)
    case 1 => (Packet.Product(version, values), remaining)
    case 2 => (Packet.Minimum(version, values), remaining)
    case 3 => (Packet.Maximum(version, values), remaining)
    case 5 => (Packet.GreaterThan(version, values(0), values(1)), remaining)
    case 6 => (Packet.LesserThan(version, values(0), values(1)), remaining)
    case 7 => (Packet.Equals(version, values(0), values(1)), remaining)
    end match
    end decodePacket

    def parse(input: String) =
    val number = input.toList.flatMap(hex => hexadecimalMapping(hex).toCharArray)
    val (operator, _) = decodePacket(number)
    operator

    def part1(input: String) =
    val packet = parse(input)
    packet.versionSum

    def part2(input: String) =
    val packet = parse(input)
    packet.value
    end part2

    You might have noticed that we had to slightly modify the versionsSum function to work with our new structure.

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day17/index.html b/puzzles/day17/index.html index 9364212f6..d6628afe5 100644 --- a/puzzles/day17/index.html +++ b/puzzles/day17/index.html @@ -5,7 +5,7 @@ Day 17: Trick Shot | Scala Center Advent of Code - + @@ -102,7 +102,7 @@ edge of the target (to travel to the furthest edge in one step).

    We adapt allMaxHeights with this new rule:

    def allMaxHeights(target: Target)(positiveOnly: Boolean): Seq[Int] =
    val Target(xs, ys) = target
    val upperBoundX = xs.max
    val upperBoundY = -ys.min -1
    val lowerBoundY = if positiveOnly then 0 else ys.min
    for
    vx <- 0 to upperBoundX
    vy <- lowerBoundY to upperBoundY
    maxy <- simulate(Probe(initial, Velocity(vx, vy)), target)
    yield
    maxy

    Computing the Solution

    As our input has not changed, we can update part 1 and give the code for part 2 as follows:

    def part1(input: String) =
    allMaxHeights(Input(input.trim))(positiveOnly = true).max

    def part2(input: String) =
    allMaxHeights(Input(input.trim))(positiveOnly = false).size

    Notice that in part 2 we only need the number of possible max heights, rather than find the highest.

    Final Code

    case class Target(xs: Range, ys: Range)

    case class Velocity(x: Int, y: Int)

    case class Position(x: Int, y: Int)

    val initial = Position(x = 0, y = 0)

    case class Probe(position: Position, velocity: Velocity)

    def step(probe: Probe): Probe =
    val Probe(Position(px, py), Velocity(vx, vy)) = probe
    Probe(Position(px + vx, py + vy), Velocity(vx - vx.sign, vy - 1))

    def collides(probe: Probe, target: Target): Boolean =
    val Probe(Position(px, py), _) = probe
    val Target(xs, ys) = target
    xs.contains(px) && ys.contains(py)

    def beyond(probe: Probe, target: Target): Boolean =
    val Probe(Position(px, py), Velocity(vx, vy)) = probe
    val Target(xs, ys) = target
    val beyondX = (vx == 0 && px < xs.min) || px > xs.max
    val beyondY = vy < 0 && py < ys.min
    beyondX || beyondY

    def simulate(probe: Probe, target: Target): Option[Int] =
    LazyList
    .iterate((probe, 0))((probe, maxY) => (step(probe), maxY `max` probe.position.y))
    .dropWhile((probe, _) => !collides(probe, target) && !beyond(probe, target))
    .headOption
    .collect { case (probe, maxY) if collides(probe, target) => maxY }

    def allMaxHeights(target: Target)(positiveOnly: Boolean): Seq[Int] =
    val upperBoundX = target.xs.max
    val upperBoundY = target.ys.min.abs
    val lowerBoundY = if positiveOnly then 0 else -upperBoundY
    for
    vx <- 0 to upperBoundX
    vy <- lowerBoundY to upperBoundY
    maxy <- simulate(Probe(initial, Velocity(vx, vy)), target)
    yield
    maxy

    type Parser[A] = PartialFunction[String, A]

    val IntOf: Parser[Int] =
    case s if s.matches(raw"-?\d+") => s.toInt

    val RangeOf: Parser[Range] =
    case s"${IntOf(begin)}..${IntOf(end)}" => begin to end

    val Input: Parser[Target] =
    case s"target area: x=${RangeOf(xs)}, y=${RangeOf(ys)}" => Target(xs, ys)

    def part1(input: String) =
    allMaxHeights(Input(input.trim))(positiveOnly = true).max

    def part2(input: String) =
    allMaxHeights(Input(input.trim))(positiveOnly = false).size

    Run it in the browser

    Part 1

    Part 2

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd advent-of-code

    You can run it with scala-cli.

    $ scala-cli 2021 -M day17.part1
    The answer is: 4851

    $ scala-cli 2021 -M day17.part2
    The answer is: 1739

    You can replace the content of the input/day14 file with your own input from adventofcode.com to get your own solution.

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day18/index.html b/puzzles/day18/index.html index 1fece06a8..57e91e9cc 100644 --- a/puzzles/day18/index.html +++ b/puzzles/day18/index.html @@ -5,14 +5,14 @@ Day 18: Snailfish | Scala Center Advent of Code - +
    Skip to main content
    - + \ No newline at end of file diff --git a/puzzles/day19/index.html b/puzzles/day19/index.html index 84a2a97b1..df79d4f2f 100644 --- a/puzzles/day19/index.html +++ b/puzzles/day19/index.html @@ -5,14 +5,14 @@ Day 19: Beacon Scanner | Scala Center Advent of Code - +
    Skip to main content
    - + \ No newline at end of file diff --git a/puzzles/day2/index.html b/puzzles/day2/index.html index a17f407ad..7f52759cf 100644 --- a/puzzles/day2/index.html +++ b/puzzles/day2/index.html @@ -5,7 +5,7 @@ Day 2: Dive! | Scala Center Advent of Code - + @@ -19,7 +19,7 @@ and then add a method move that will translate the puzzle's rules to a position.

    case class Position(horizontal: Int, depth: Int):
    def move(p: Command): Position =
    p match
    case Command.Forward(x) => Position(horizontal + x, depth)
    case Command.Down(x) => Position(horizontal, depth + x)
    case Command.Up(x) => Position(horizontal, depth - x)

    To apply all the commands from the input file, we use foldLeft

    val firstPosition = Position(0, 0)
    val lastPosition = entries.foldLeft(firstPosition)((position, command) => position.move(command))

    foldLeft is a method from the standard library on iterable collections: Seq, List, Iterator...

    It's a super convenient method that allows to iterate from left to right on a list.

    The signature of foldLeft is:

    def foldLeft[B](initialElement: B)(op: (B, A) => B): B

    Let's see an example:

    // Implementing a sum on a List
    List(1, 3, 2, 4).foldLeft(0)((accumulator, current) => accumulator + current) // 10

    It is the same as:

    (((0 + 1) + 3) + 2) + 4

    Final code for part 1

    def part1(input: String): Int =
    val entries = input.linesIterator.map(Command.from)
    val firstPosition = Position(0, 0)
    // we iterate on each entry and move it following the received command
    val lastPosition = entries.foldLeft(firstPosition)((position, command) => position.move(command))
    lastPosition.result

    case class Position(horizontal: Int, depth: Int):
    def move(p: Command): Position =
    p match
    case Command.Forward(x) => Position(horizontal + x, depth)
    case Command.Down(x) => Position(horizontal, depth + x)
    case Command.Up(x) => Position(horizontal, depth - x)

    def result = horizontal * depth

    enum Command:
    case Forward(x: Int)
    case Down(x: Int)
    case Up(x: Int)

    object Command:
    def from(s: String): Command =
    s match
    case s"forward $x" if x.toIntOption.isDefined => Forward(x.toInt)
    case s"up $x" if x.toIntOption.isDefined => Up(x.toInt)
    case s"down $x" if x.toIntOption.isDefined => Down(x.toInt)
    case _ => throw new Exception(s"value $s is not valid command")

    Solution of Part 2

    The part 2 introduces new rules to move the sonar. So we need a new position that takes into account the aim and a new method move with the new rules. The remaining code remains the same.

    Moving the sonar part 2

    case class PositionWithAim(horizontal: Int, depth: Int, aim: Int):
    def move(p: Command): PositionWithAim =
    p match
    case Command.Forward(x) => PositionWithAim(horizontal + x, depth + x * aim, aim)
    case Command.Down(x) => PositionWithAim(horizontal, depth, aim + x)
    case Command.Up(x) => PositionWithAim(horizontal, depth, aim - x)

    Final code for part 2

    case class PositionWithAim(horizontal: Int, depth: Int, aim: Int):
    def move(p: Command): PositionWithAim =
    p match
    case Command.Forward(x) => PositionWithAim(horizontal + x, depth + x * aim, aim)
    case Command.Down(x) => PositionWithAim(horizontal, depth, aim + x)
    case Command.Up(x) => PositionWithAim(horizontal, depth, aim - x)

    def result = horizontal * depth

    enum Command:
    case Forward(x: Int)
    case Down(x: Int)
    case Up(x: Int)

    object Command:
    def from(s: String): Command =
    s match
    case s"forward $x" if x.toIntOption.isDefined => Forward(x.toInt)
    case s"up $x" if x.toIntOption.isDefined => Up(x.toInt)
    case s"down $x" if x.toIntOption.isDefined => Down(x.toInt)
    case _ => throw new Exception(s"value $s is not valid command")

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd scala-advent-of-code

    The you can run it with scala-cli:

    $ scala-cli 2021 -M day2.part1
    The answer is 2070300

    $ scala-cli 2021 -M day2.part2
    The answer is 2078985210

    You can replace the content of the input/day2 file with your own input from adventofcode.com to get your own solution.

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day20/index.html b/puzzles/day20/index.html index d94906e58..daacea078 100644 --- a/puzzles/day20/index.html +++ b/puzzles/day20/index.html @@ -5,7 +5,7 @@ Day 20: Trench Map | Scala Center Advent of Code - + @@ -52,7 +52,7 @@ element n. Then, we compute its 50th element by calling .apply(50). As a consequence, only the first 50 elements will be computed at all.

    Finally, we call countLitPixels() on the output image to count its number of lit pixels.

    Run it in the browser

    Part 1

    Part 2

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd scala-advent-of-code

    You can run it with scala-cli.

    $ scala-cli 2021 -M day20.part1
    The solution is: 5301
    $ scala-cli 2021 -M day20.part2
    The solution is: 19492

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day21/index.html b/puzzles/day21/index.html index fe51aa1b7..25cac846b 100644 --- a/puzzles/day21/index.html +++ b/puzzles/day21/index.html @@ -5,7 +5,7 @@ Day 21: Dirac Dice | Scala Center Advent of Code - + @@ -23,7 +23,7 @@ There are only 7 different outcomes to the roll of three dice, with most of them occurring several times. The rest of the game is not affected by anything but the sum, although it will happen in several universes, which we need to count. We can implement that by remembering in how many universes the current state of the game gets played, and add that amount to the number of times player 1 or 2 wins.

    We first compute how many times each outcome happens:

    /** For each 3-die throw, how many of each total sum do we have? */
    val dieCombinations: List[(Int, Long)] =
    val possibleRolls: List[Int] =
    for
    die1 <- List(1, 2, 3)
    die2 <- List(1, 2, 3)
    die3 <- List(1, 2, 3)
    yield
    die1 + die2 + die3
    possibleRolls.groupMapReduce(identity)(_ => 1L)(_ + _).toList

    Then, we add a parameter inHowManyUniverses to playWithDiracDie, and multiply it in the recursive calls by the number of times that each outcome happens:

    def playWithDiracDie(players: Players, player1Turn: Boolean, wins: Wins, inHowManyUniverses: Long): Unit =
    for (diesValue, count) <- dieCombinations do
    val newInHowManyUniverses = inHowManyUniverses * count
    val player = players(0)
    val newCell = (player.cell + diesValue) % 10
    val newScore = player.score + (newCell + 1)
    if newScore >= 21 then
    if player1Turn then
    wins.player1Wins += newInHowManyUniverses
    else
    wins.player2Wins += newInHowManyUniverses
    else
    val newPlayer = Player(newCell, newScore)
    playWithDiracDie((players(1), newPlayer), !player1Turn, wins, newInHowManyUniverses)
    end for

    We start with 1 universe, so the initial call to playWithDiracDie is:

    playWithDiracDie(players, player1Turn = true, wins, inHowManyUniverses = 1L)

    The reduction of the branching factor from 27 to 7 is enough to simulate all the possible universes in seconds, whereas I stopped waiting for the naive solution after a few minutes.

    Solution for part 2

    Here is the full code for part 2:

    final class Wins(var player1Wins: Long, var player2Wins: Long)

    def part2(input: String): Long =
    val players = parseInput(input)
    val wins = new Wins(0L, 0L)
    playWithDiracDie(players, player1Turn = true, wins, inHowManyUniverses = 1L)
    Math.max(wins.player1Wins, wins.player2Wins)

    /** For each 3-die throw, how many of each total sum do we have? */
    val dieCombinations: List[(Int, Long)] =
    val possibleRolls: List[Int] =
    for
    die1 <- List(1, 2, 3)
    die2 <- List(1, 2, 3)
    die3 <- List(1, 2, 3)
    yield
    die1 + die2 + die3
    possibleRolls.groupMapReduce(identity)(_ => 1L)(_ + _).toList

    def playWithDiracDie(players: Players, player1Turn: Boolean, wins: Wins, inHowManyUniverses: Long): Unit =
    for (diesValue, count) <- dieCombinations do
    val newInHowManyUniverses = inHowManyUniverses * count
    val player = players(0)
    val newCell = (player.cell + diesValue) % 10
    val newScore = player.score + (newCell + 1)
    if newScore >= 21 then
    if player1Turn then
    wins.player1Wins += newInHowManyUniverses
    else
    wins.player2Wins += newInHowManyUniverses
    else
    val newPlayer = Player(newCell, newScore)
    playWithDiracDie((players(1), newPlayer), !player1Turn, wins, newInHowManyUniverses)
    end for

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd scala-advent-of-code

    You can run it with scala-cli.

    $ scala-cli 2021 -M day21.part1
    The answer is: 855624

    $ scala-cli 2021 -M day21.part2
    The answer is: 187451244607486

    You can replace the content of the input/day21 file with your own input from adventofcode.com to get your own solution.

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day22/index.html b/puzzles/day22/index.html index 1b877ab74..821f3b6de 100644 --- a/puzzles/day22/index.html +++ b/puzzles/day22/index.html @@ -5,7 +5,7 @@ Day 22: Reactor Reboot | Scala Center Advent of Code - + @@ -68,7 +68,7 @@ only while they fit the initialisation sequence, and then summarise the set of cuboids:

    def part1(input: String): BigInt =
    val steps = input.linesIterator.map(StepOf)
    summary(run(steps.takeWhile(s => isInit(s.cuboid))))

    Solution of Part 2

    Part 2 is identical to part 1, except that we run all steps, not just the initialisation sequence:

    def part2(input: String): BigInt =
    summary(run(input.linesIterator.map(StepOf)))

    Run it in the browser

    Part 1

    Part 2

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd scala-advent-of-code

    You can run it with scala-cli.

    $ scala-cli 2021 -M day22.part1
    The answer is: 647062

    $ scala-cli 2021 -M day22.part2
    The answer is: 1319618626668022

    You can replace the content of the input/day22 file with your own input from adventofcode.com to get your own solution.

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day23/index.html b/puzzles/day23/index.html index 863eddcea..bf9de0e89 100644 --- a/puzzles/day23/index.html +++ b/puzzles/day23/index.html @@ -5,7 +5,7 @@ Day 23: Amphipod | Scala Center Advent of Code - + @@ -14,7 +14,7 @@ Our intuition here is that the puzzle can be modeled as a graph and solved using Dijkstra's algorithm.

    A graph of situations

    We can think of the puzzle as a graph of situations, where a node is an instance of Situation and an edge is an amphipod's move whose weight is the energy cost of the move.

    In such a graph, two situations are connected if there is an amphipod move that transform the first situation into the second.

    Implementing the Dijkstra's solver

    We want to find the minimal energy cost to go from the initial situation to the final situation, where all amphipods are located in their destination room. This is the energy cost of the shortest path between the two situations in the graph described above. We can use Dijkstra's algorithm to find it.

    Here is our implementation:

    class DijkstraSolver(initialSituation: Situation):
    private val bestSituations = mutable.Map(initialSituation -> 0)
    private val situationsToExplore =
    mutable.PriorityQueue((initialSituation, 0))(Ordering.by((_, energy) => -energy))

    @tailrec
    final def solve(): Energy =
    val (situation, energy) = situationsToExplore.dequeue
    if situation.isFinal then energy
    else if bestSituations(situation) < energy then solve()
    else
    for
    (nextSituation, consumedEnergy) <- situation.moveAllAmphipodsOnce
    nextEnergy = energy + consumedEnergy
    knownEnergy = bestSituations.getOrElse(nextSituation, Int.MaxValue)
    if nextEnergy < knownEnergy
    do
    bestSituations.update(nextSituation, nextEnergy)
    situationsToExplore.enqueue((nextSituation, nextEnergy))
    solve()

    At the beginning we only know the cost of the initial situation which is 0.

    The solve method is recursive:

    1. First we dequeue the best known situation in the situationToExplore queue.
    2. If it is the final situation, we return the associated energy cost.
    3. If it is not:

    Final solution

    // using scala 3.1.0

    package day23

    import scala.util.Using
    import scala.io.Source
    import scala.annotation.tailrec
    import scala.collection.mutable


    @main def part1(): Unit =
    val answer = part1(readInput())
    println(s"The answer is: $answer")

    @main def part2(): Unit =
    val answer = part2(readInput())
    println(s"The answer is: $answer")

    def readInput(): String =
    Using.resource(Source.fromFile("input/day23"))(_.mkString)

    case class Position(x: Int, y: Int)

    enum Room(val x: Int):
    case A extends Room(3)
    case B extends Room(5)
    case C extends Room(7)
    case D extends Room(9)

    type Energy = Int

    enum Amphipod(val energy: Energy, val destination: Room):
    case A extends Amphipod(1, Room.A)
    case B extends Amphipod(10, Room.B)
    case C extends Amphipod(100, Room.C)
    case D extends Amphipod(1000, Room.D)

    object Amphipod:
    def tryParse(input: Char): Option[Amphipod] =
    input match
    case 'A' => Some(Amphipod.A)
    case 'B' => Some(Amphipod.B)
    case 'C' => Some(Amphipod.C)
    case 'D' => Some(Amphipod.D)
    case _ => None

    val hallwayStops: Seq[Position] = Seq(
    Position(1, 1),
    Position(2, 1),
    Position(4, 1),
    Position(6, 1),
    Position(8, 1),
    Position(10, 1),
    Position(11, 1)
    )

    case class Situation(positions: Map[Position, Amphipod], roomSize: Int):
    def moveAllAmphipodsOnce: Seq[(Situation, Energy)] =
    for
    (start, amphipod) <- positions.toSeq
    stop <- nextStops(amphipod, start)
    path = getPath(start, stop)
    if path.forall(isEmpty)
    yield
    val newPositions = positions - start + (stop -> amphipod)
    val energy = path.size * amphipod.energy
    (copy(positions = newPositions), energy)

    def isFinal =
    positions.forall((position, amphipod) => position.x == amphipod.destination.x)

    /**
    * Return a list of positions to which an amphipod at position `from` can go:
    * - If the amphipod is in its destination room and the room is free it must not go anywhere.
    * - If the amphipod is in its destination room and the room is not free it can go to the hallway.
    * - If the amphipod is in the hallway it can only go to its destination.
    * - Otherwise it can go to the hallway.
    */
    private def nextStops(amphipod: Amphipod, from: Position): Seq[Position] =
    from match
    case Position(x, y) if x == amphipod.destination.x =>
    if isDestinationFree(amphipod) then Seq.empty
    else hallwayStops
    case Position(_, 1) =>
    if isDestinationFree(amphipod) then
    (roomSize + 1).to(2, step = -1)
    .map(y => Position(amphipod.destination.x, y))
    .find(isEmpty)
    .toSeq
    else Seq.empty
    case _ => hallwayStops


    private def isDestinationFree(amphipod: Amphipod): Boolean =
    2.to(roomSize + 1)
    .flatMap(y => positions.get(Position(amphipod.destination.x, y)))
    .forall(_ == amphipod)

    // Build the path to go from `start` to `stop`
    private def getPath(start: Position, stop: Position): Seq[Position] =
    val hallway =
    if start.x < stop.x
    then (start.x + 1).to(stop.x).map(Position(_, 1))
    else (start.x - 1).to(stop.x, step = -1).map(Position(_, 1))
    val startRoom = (start.y - 1).to(1, step = -1).map(Position(start.x, _))
    val stopRoom = 2.to(stop.y).map(Position(stop.x, _))
    startRoom ++ hallway ++ stopRoom

    private def isEmpty(position: Position) =
    !positions.contains(position)

    object Situation:
    def parse(input: String, roomSize: Int): Situation =
    val positions =
    for
    (line, y) <- input.linesIterator.zipWithIndex
    (char, x) <- line.zipWithIndex
    amphipod <- Amphipod.tryParse(char)
    yield Position(x, y) -> amphipod
    Situation(positions.toMap, roomSize)

    class DijkstraSolver(initialSituation: Situation):
    private val bestSituations = mutable.Map(initialSituation -> 0)
    private val situationsToExplore =
    mutable.PriorityQueue((initialSituation, 0))(Ordering.by((_, energy) => -energy))

    @tailrec
    final def solve(): Energy =
    val (situation, energy) = situationsToExplore.dequeue
    if situation.isFinal then energy
    else if bestSituations(situation) < energy then solve()
    else
    for
    (nextSituation, consumedEnergy) <- situation.moveAllAmphipodsOnce
    nextEnergy = energy + consumedEnergy
    knownEnergy = bestSituations.getOrElse(nextSituation, Int.MaxValue)
    if nextEnergy < knownEnergy
    do
    bestSituations.update(nextSituation, nextEnergy)
    situationsToExplore.enqueue((nextSituation, nextEnergy))
    solve()

    def part1(input: String): Energy =
    val initialSituation = Situation.parse(input, roomSize = 2)
    DijkstraSolver(initialSituation).solve()

    def part2(input: String): Energy =
    val lines = input.linesIterator
    val unfoldedInput = (lines.take(3) ++ Seq(" #D#C#B#A#", " #D#B#A#C#") ++ lines.take(2)).mkString("\n")
    val initialSituation = Situation.parse(unfoldedInput, roomSize = 4)
    DijkstraSolver(initialSituation).solve()

    Run it in the browser

    Part 1

    Part 2

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd scala-advent-of-code

    You can run it with scala-cli.

    $ scala-cli 2021 -M day21.part1
    The answer is: 855624

    $ scala-cli 2021 -M day21.part2
    The answer is: 187451244607486

    You can replace the content of the input/day21 file with your own input from adventofcode.com to get your own solution.

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day24/index.html b/puzzles/day24/index.html index fc697d191..c53301f8d 100644 --- a/puzzles/day24/index.html +++ b/puzzles/day24/index.html @@ -5,14 +5,14 @@ Day 24: Arithmetic Logic Unit | Scala Center Advent of Code - +
    Skip to main content
    - + \ No newline at end of file diff --git a/puzzles/day25/index.html b/puzzles/day25/index.html index a58837cc2..e2bd32902 100644 --- a/puzzles/day25/index.html +++ b/puzzles/day25/index.html @@ -5,14 +5,14 @@ Day 25: Sea Cucumber | Scala Center Advent of Code - +
    Skip to main content

    Day 25: Sea Cucumber

    by @Sporarum, student at EPFL, and @adpi2

    Puzzle description

    https://adventofcode.com/2021/day/25

    Solution of Part 1

    enum SeaCucumber:
    case Empty, East, South

    object SeaCucumber:
    def fromChar(c: Char) = c match
    case '.' => Empty
    case '>' => East
    case 'v' => South

    type Board = Seq[Seq[SeaCucumber]]

    def part1(input: String): Int =
    val board: Board = input.linesIterator.map(_.map(SeaCucumber.fromChar(_))).toSeq
    fixedPoint(board)

    def fixedPoint(board: Board, step: Int = 1): Int =
    val next = move(board)
    if board == next then step else fixedPoint(next, step + 1)

    def move(board: Board) = moveSouth(moveEast(board))
    def moveEast(board: Board) = moveImpl(board, SeaCucumber.East)
    def moveSouth(board: Board) = moveImpl(board.transpose, SeaCucumber.South).transpose

    def moveImpl(board: Board, cucumber: SeaCucumber): Board =
    board.map { l =>
    zip3(l.last +: l.init, l, (l.tail :+ l.head)).map{
    case (`cucumber`, SeaCucumber.Empty, _) => `cucumber`
    case (_, `cucumber`, SeaCucumber.Empty) => SeaCucumber.Empty
    case (_, curr, _) => curr
    }
    }

    def zip3[A,B,C](l1: Seq[A], l2: Seq[B], l3: Seq[C]): Seq[(A,B,C)] =
    l1.zip(l2).zip(l3).map { case ((a, b), c) => (a,b,c) }

    Run it in the browser

    Part 1

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd scala-advent-of-code

    You can run it with scala-cli.

    $ scala-cli 2021 -M day25.part1
    The answer is: 435

    You can replace the content of the input/day25 file with your own input from adventofcode.com to get your own solution.

    Solutions from the community

    Share your solution to the Scala community by editing this page. You can even write the whole article! See here for the expected format

    - + \ No newline at end of file diff --git a/puzzles/day3/index.html b/puzzles/day3/index.html index 09db05785..7c61c44a9 100644 --- a/puzzles/day3/index.html +++ b/puzzles/day3/index.html @@ -5,7 +5,7 @@ Day 3: Binary Diagnostic | Scala Center Advent of Code - + @@ -34,7 +34,7 @@ Here is an example of partition that separates odd numbers from even numbers:

    val numbers = List(4, 6, 5, 12, 75, 3, 10)
    val (oddNumbers, evenNumbers) = numbers.partition(x => x % 2 != 0)
    // oddNumbers = List(5, 75, 3)
    // evenNumbers = List(4, 6, 12, 10)

    We use it as follows to separate our lines in two lists:

    val (bitLinesWithOne, bitLinesWithZero) =
    bitLines.partition(line => line(bitPosition) == 1)

    We can determine whether there are more 1s than 0s (or a tie) by comparing the size of the two lists. Comparing the sizes of two collections is best done with sizeCompare:

    val onesAreMostCommon = bitLinesWithOne.sizeCompare(bitLinesWithZero) >= 0

    Finally, we decide which list we keep to go further:

    val bitLinesToKeep =
    if onesAreMostCommon then
    if keepMostCommon then bitLinesWithOne else bitLinesWithZero
    else
    if keepMostCommon then bitLinesWithZero else bitLinesWithOne
    recursiveFilter(bitLinesToKeep, bitPosition + 1, keepMostCommon)

    (The two tests could be combined as if onesAreMostCommon == keepMostCommon, but I found that less readable.)

    Final code for part 2

    def part2(input: String): Int =
    val bitLines: List[BitLine] = input.linesIterator.map(parseBitLine).toList

    val oxygenGeneratorRatingLine: BitLine =
    recursiveFilter(bitLines, 0, keepMostCommon = true)
    val oxygenGeneratorRating = bitLineToInt(oxygenGeneratorRatingLine)

    val co2ScrubberRatingLine: BitLine =
    recursiveFilter(bitLines, 0, keepMostCommon = false)
    val co2ScrubberRating = bitLineToInt(co2ScrubberRatingLine)

    oxygenGeneratorRating * co2ScrubberRating

    @scala.annotation.tailrec
    def recursiveFilter(bitLines: List[BitLine], bitPosition: Int,
    keepMostCommon: Boolean): BitLine =
    bitLines match
    case Nil =>
    throw new AssertionError("this shouldn't have happened")
    case lastRemainingLine :: Nil =>
    lastRemainingLine
    case _ =>
    val (bitLinesWithOne, bitLinesWithZero) =
    bitLines.partition(line => line(bitPosition) == 1)
    val onesAreMostCommon = bitLinesWithOne.sizeCompare(bitLinesWithZero) >= 0
    val bitLinesToKeep =
    if onesAreMostCommon then
    if keepMostCommon then bitLinesWithOne else bitLinesWithZero
    else
    if keepMostCommon then bitLinesWithZero else bitLinesWithOne
    recursiveFilter(bitLinesToKeep, bitPosition + 1, keepMostCommon)

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd scala-advent-of-code

    You can run it with scala-cli. Since today's solution is written in Scala.js, you will need a local setup of Node.js to run it.

    $ scala-cli 2021 -M day3.part1 --js-module-kind commonjs
    The answer is 1025636

    $ scala-cli 2021 -M day3.part2 --js-module-kind commonjs
    The answer is 793873

    You can replace the content of the input/day3 file with your own input from adventofcode.com to get your own solution.

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day4/index.html b/puzzles/day4/index.html index 238d68d17..7f8d37820 100644 --- a/puzzles/day4/index.html +++ b/puzzles/day4/index.html @@ -5,7 +5,7 @@ Day 4: Giant Squid | Scala Center Advent of Code - + @@ -24,7 +24,7 @@ We filter them with lines.filter(_ > turn).

    However, only taking the sum would be wrong, as we are using the turns, and not the original numbers! We thus need to map them to their original values:

    val sumNumsNotDrawn = board.lines.map{ line =>
    line.filter(_ > turn).map(turnToNumber(_)).sum
    }.sum

    The score is then:

    turnToNumber(turn) * sumUnmarkedNums

    Solution of Part 1

    In part one, we have to compute the score of the first board to win. This is the board whith the smallest winning turn.

    val (winnerBoard, winnerTurn) = winningTurns.minBy((_, turn) => turn)

    And so the score is:

    val winnerScore = score(winnerBoard, winnerTurn)

    Solution of Part 2

    In part two, we have to find the score of the last board to win, so we swap the minBy by a maxBy to get our result:

    val (loserBoard, loserTurn) = winningTurns.maxBy((_, turn) => turn)
    val loserScore = score(loserBoard, loserTurn)

    Run it in the browser

    Part 1

    Part 2

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd scala-advent-of-code

    You can run it with scala-cli.

    $ scala-cli 2021 -M day4.run
    The answer of part 1 is 14093.
    The answer of part 2 is 17388.

    You can replace the content of the input/day4 file with your own input from adventofcode.com to get your own solution.

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day5/index.html b/puzzles/day5/index.html index 78a91966e..91b3265b7 100644 --- a/puzzles/day5/index.html +++ b/puzzles/day5/index.html @@ -5,7 +5,7 @@ Day 5: Hydrothermal Venture | Scala Center Advent of Code - + @@ -24,7 +24,7 @@ both x and y positions increment by 1 at each step of the range. So we can add additional condition to our solution:

    else for (px, py) <- rangex.zip(rangey) do update(Point(px, py))

    We can just use the 2 previously defined ranges for this. So the full method will look like this:

    def findDangerousPoints(vents: Seq[Vent]) =
    val map = mutable.Map[Point, Int]().withDefaultValue(0)
    def update(p: Point) =
    val current = map(p)
    map.update(p, current + 1)

    for vent <- vents do
    def rangex =
    val stepx = if vent.end.x > vent.start.x then 1 else -1
    vent.start.x.to(vent.end.x, stepx)
    def rangey =
    val stepy = if vent.end.y > vent.start.y then 1 else -1
    vent.start.y.to(vent.end.y, stepy)
    // vent is horizontal
    if vent.start.x == vent.end.x then
    for py <- rangey do update(Point(vent.start.x, py))
    // vent is vertical
    else if vent.start.y == vent.end.y then
    for px <- rangex do update(Point(px, vent.start.y))
    // vent is diagonal
    else for (px, py) <- rangex.zip(rangey) do update(Point(px, py))
    end for

    map.count { case (_, v) => v > 1 }
    end findDangerousPoints

    Run solution in the browser

    Part 1

    Part 2

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd scala-advent-of-code

    You can run it with scala-cli.

    $ scala-cli 2021 -M day5.part1
    The answer is: 7674

    $ scala-cli 2021 -M day5.part2
    The answer is: 20898

    You can replace the content of the input/day5 file with your own input from adventofcode.com to get your own solution.

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day6/index.html b/puzzles/day6/index.html index 2c99e37b8..6e0490e08 100644 --- a/puzzles/day6/index.html +++ b/puzzles/day6/index.html @@ -5,7 +5,7 @@ Day 6: Lanternfish | Scala Center Advent of Code - + @@ -68,7 +68,7 @@ achieves this by summing the groups of fish: the method values returns a collection of groups of fish (each containing the number of fish in that group), finally the method sum sums up the groups.

    Final code for part 2

    // "How many lanternfish would there be after 256 days?"
    def part2(input: String): BigInt =
    simulate(
    days = 256,
    Fish.parseSeveral(input).groupMapReduce(_.timer)(_ => BigInt(1))(_ + _)
    )

    def simulate(days: Int, initialPopulation: Map[Int, BigInt]): BigInt =
    (1 to days)
    .foldLeft(initialPopulation)((population, _) => tick(population))
    .values
    .sum

    def tick(population: Map[Int, BigInt]): Map[Int, BigInt] =
    def countPopulation(daysLeft: Int): BigInt = population.getOrElse(daysLeft, BigInt(0))
    Map(
    0 -> countPopulation(1),
    1 -> countPopulation(2),
    2 -> countPopulation(3),
    3 -> countPopulation(4),
    4 -> countPopulation(5),
    5 -> countPopulation(6),
    6 -> (countPopulation(7) + countPopulation(0)),
    7 -> countPopulation(8),
    8 -> countPopulation(0)
    )

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd scala-advent-of-code

    You can run it with scala-cli.

    $ scala-cli 2021 -M day6.part1
    The solution is 345793

    $ scala-cli 2021 -M day6.part2
    The solution is 1572643095893

    You can replace the content of the input/day6 file with your own input from adventofcode.com to get your own solution.

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day7/index.html b/puzzles/day7/index.html index 1f0b8fb68..1348bc405 100644 --- a/puzzles/day7/index.html +++ b/puzzles/day7/index.html @@ -5,7 +5,7 @@ Day 7: The Treachery of Whales | Scala Center Advent of Code - + @@ -40,7 +40,7 @@ solution.

    Solutions from the community

    There are most likely some other solutions that we could have used. In particular some advent coders had luck with using median and average for determining the final horizontal positions of the crabmarines.

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day8/index.html b/puzzles/day8/index.html index 5653fae18..ccb102cd5 100644 --- a/puzzles/day8/index.html +++ b/puzzles/day8/index.html @@ -5,7 +5,7 @@ Day 8: Seven Segment Search | Scala Center Advent of Code - + @@ -82,7 +82,7 @@ Each display has 4 digits, so after decoding the digits we will have a sequence of 4 Digit.

    To convert a sequence of Digit to an integer value, we can convert each digit to its corresponding integer representation by calling .ordinal, and then we can accumulate a sum by (from the left), multiplying the current total by 10 for each new digit, and then adding the current digit:

    def digitsToInt(digits: Seq[Digit]): Int =
    digits.foldLeft(0)((acc, d) => acc * 10 + d.ordinal)

    Final Result

    Finally, we use our digitsToInt function to convert each solution to an integer value, and sum the result:

    solutions.map(digitsToInt).sum

    Final Code

    The final code for part 2 can be appended to the code of part 1:

    import Digit.*

    def part2(input: String): Int =

    def parseSegmentsSeq(segments: String): Seq[Segments] =
    segments.trim.split(" ").toSeq.map(Segment.parseSegments)

    def splitParts(line: String): (Seq[Segments], Seq[Segments]) =
    val Array(cipher, plaintext) = line.split('|').map(parseSegmentsSeq)
    (cipher, plaintext)

    def digitsToInt(digits: Seq[Digit]): Int =
    digits.foldLeft(0)((acc, d) => acc * 10 + d.ordinal)

    val problems = input.linesIterator.map(splitParts)

    val solutions = problems.map((cipher, plaintext) =>
    plaintext.map(substitutions(cipher))
    )

    solutions.map(digitsToInt).sum

    end part2

    def substitutions(cipher: Seq[Segments]): Map[Segments, Digit] =

    def lookup(section: Seq[Segments], withSegments: Segments): (Segments, Seq[Segments]) =
    val (Seq(uniqueMatch), remaining) = section.partition(withSegments.subsetOf)
    (uniqueMatch, remaining)

    val uniques: Map[Digit, Segments] =
    Map.from(
    for
    segments <- cipher
    digit <- Digit.lookupUnique(segments)
    yield
    digit -> segments
    )

    val ofSizeFive = cipher.filter(_.sizeIs == 5)
    val ofSizeSix = cipher.filter(_.sizeIs == 6)

    val one = uniques(One)
    val four = uniques(Four)
    val seven = uniques(Seven)
    val eight = uniques(Eight)
    val (three, remainingFives) = lookup(ofSizeFive, withSegments = one)
    val (nine, remainingSixes) = lookup(ofSizeSix, withSegments = three)
    val (zero, Seq(six)) = lookup(remainingSixes, withSegments = seven)
    val (five, Seq(two)) = lookup(remainingFives, withSegments = four &~ one)

    val decode: Map[Segments, Digit] =
    Seq(zero, one, two, three, four, five, six, seven, eight, nine)
    .zip(Digit.index)
    .toMap

    decode
    end substitutions

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd scala-advent-of-code

    You can run it with scala-cli.

    $ scala-cli 2021 -M day8.part1
    The solution is 521

    $ scala-cli 2021 -M day8.part2
    The solution is 1016804

    You can replace the content of the input/day8 file with your own input from adventofcode.com to get your own solution.

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/puzzles/day9/index.html b/puzzles/day9/index.html index 6f1e55bac..e33cd0a7a 100644 --- a/puzzles/day9/index.html +++ b/puzzles/day9/index.html @@ -5,7 +5,7 @@ Day 9: Smoke Basin | Scala Center Advent of Code - + @@ -37,7 +37,7 @@ retrieve neighbors of neighbors, I add the cells that still need to be processed in the queue. The algorithm stops when there are no more cells to visit:

    def basin(lowPoint: Position, heightMap: Heightmap): Set[Position] =
    @scala.annotation.tailrec
    def iter(visited: Set[Position], toVisit: Queue[Position], basinAcc: Set[Position]): Set[Position] =
    // No cells to visit, we are done
    if toVisit.isEmpty then basinAcc
    else
    // Select next cell to visit
    val (currentPos, remaining) = toVisit.dequeue
    // Collect the neighboring cells that should be part of the basin
    val newNodes = heightMap.neighborsOf(currentPos).toList.collect {
    case (pos, height) if !visited(currentPos) && height != 9 => pos
    }
    // Continue to next neighbor
    iter(visited + currentPos, remaining ++ newNodes, basinAcc ++ newNodes)

    iter(Set.empty, Queue(lowPoint), Set(lowPoint))

    Run it locally

    You can get this solution locally by cloning the scalacenter/scala-advent-of-code repository.

    $ git clone https://github.com/scalacenter/scala-advent-of-code
    $ cd scala-advent-of-code

    You can run it with scala-cli.

    $ scala-cli 2021 -M day9.part1
    The solution is 448
    $ scala-cli 2021 -M day9.part2
    The solution is 1417248

    You can replace the content of the input/day9 file with your own input from adventofcode.com to get your own solution.

    Solutions from the community

    Share your solution to the Scala community by editing this page.

    - + \ No newline at end of file diff --git a/setup/index.html b/setup/index.html index 29511a9c4..0a985c1ed 100644 --- a/setup/index.html +++ b/setup/index.html @@ -5,7 +5,7 @@ Setup | Scala Center Advent of Code - + @@ -18,7 +18,7 @@ It supports an incredible number of languages through its extension system.

    Its more popular extension for Scala is called Metals. We will use VS Code and Metals to write and navigate Scala code.

    VS Code

    Download the right VS Code for your operating system on the download page of VS Code and then install it.

    Install Metals

    1. Open VS Code and Click the extensions icon in the left bar

    Open Extensions

    2. Search metals and click the Scala (Metals) extension and click the Install button

    Install Metals

    - + \ No newline at end of file