Nim
I don't want to talk about it. -_-
An unofficial home for the advent of code community on programming.dev!
Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.
Solution Threads
M | T | W | T | F | S | S |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 |
Icon base by Lorc under CC BY 3.0 with modifications to add a gradient
console.log('Hello World')
def countDyn(a: List[Char], b: List[Int]): Long =
// Simple dynamic programming approach
// We fill a table T, where
// T[ ai, bi ] -> number of ways to place b[bi..] in a[ai..]
// T[ ai, bi ] = 0 if an-ai >= b[bi..].sum + bn-bi
// T[ ai, bi ] = 1 if bi == b.size - 1 && ai == a.size - b[bi] - 1
// T[ ai, bi ] =
// (place) T [ ai + b[bi], bi + 1] if ? or #
// (skip) T [ ai + 1, bi ] if ? or .
//
def t(ai: Int, bi: Int, tbl: Map[(Int, Int), Long]): Long =
if ai >= a.size then
if bi >= b.size then 1L else 0L
else
val place = Option.when(
bi < b.size && // need to have piece left
ai + b(bi) <= a.size && // piece needs to fit
a.slice(ai, ai + b(bi)).forall(_ != '.') && // must be able to put piece there
(ai + b(bi) == a.size || a(ai + b(bi)) != '#') // piece needs to actually end
)((ai + b(bi) + 1, bi + 1)).flatMap(tbl.get).getOrElse(0L)
val skip = Option.when(a(ai) != '#')((ai + 1, bi)).flatMap(tbl.get).getOrElse(0L)
place + skip
@tailrec def go(ai: Int, tbl: Map[(Int, Int), Long]): Long =
if ai == 0 then t(ai, 0, tbl) else go(ai - 1, tbl ++ b.indices.inclusive.map(bi => (ai, bi) -> t(ai, bi, tbl)).toMap)
go(a.indices.inclusive.last + 1, Map())
def countLinePossibilities(repeat: Int)(a: String): Long =
a match
case s"$pattern $counts" =>
val p2 = List.fill(repeat)(pattern).mkString("?")
val c2 = List.fill(repeat)(counts).mkString(",")
countDyn(p2.toList, c2.split(",").map(_.toInt).toList)
case _ => 0L
def task1(a: List[String]): Long = a.map(countLinePossibilities(1)).sum
def task2(a: List[String]): Long = a.map(countLinePossibilities(5)).sum
(Edit: fixed mangling of &<)
I'm struggling to fully understand your solution. Could you tell me, why do you return 1
when at the end of a
and b
? And why do you start from size + 1
?
T counts the number of ways to place the blocks with lengths specified in b in the remaining a.size - ai slots. If there are no more slots left, there are two cases: Either there are also no more blocks left, then everything is fine, and the current situation is 1 way to place the blocks in the slots. Otherwise, there are still blocks left, and no more space to place them in. This means the current sitution is incorrect, so we contribute 0 ways to place the blocks. This is what the if bi >= b.size then 1L else 0L
{.scala} does.
The start at size + 1
is necessary, as we need to compute every table entry before it may get looked up. When placing the last block, we may check the entry (ai + b(bi) + 1, bi + 1)
, where ai + b(bi)
may already equal a.size
(in the case where the block ends exactly at the end of a
). The + 1
in the entry is necessary, as we need to skip a slot after every block: If we looked at (ai + b(bi), bi + 1)
, we could start at a.size
, but then, for e.g. b = [2, 3]
, we would consider ...#####.
a valid placement.
Let me know if there are still things unclear :)
Thanks for the detailed explanation. It helped a lot, especially what the tbl
actually holds.
I've read your code again and I get how it works, but it still feels kinda strange that we are considering values outside of range of a
and b
, and that we are marking them as correct. Like in first row of the example ???.### 1,1,3
, there is no spring at 8
and no group at 3
but we are marking (8,3)
and (7,3)
as correct. In my mind, first position that should be marked as correct is 4,2
, because that's where group of 3 can fit.
If you make the recurrent case a little more complicated, you can sidestep the weird base cases, but I like reducing the endpoints down to things like this that are easily implementable, even if they sound a little weird at first.
You are probably right. Just my rumblings. Thanks for the help.
Let me know if you have any questions or feedback!
import dataclasses
import functools
from .solver import Solver
class MatchState:
pass
@dataclasses.dataclass
class NotMatching(MatchState):
pass
@dataclasses.dataclass
class Matching(MatchState):
current_length: int
desired_length: int
@functools.cache
def _match_one_template(template: str, groups: tuple[int, ...]) -> int:
if not groups:
if '#' in template:
return 0
else:
return 1
state: MatchState = NotMatching()
remaining_groups: list[int] = list(groups)
options_in_other_branches: int = 0
for i in range(len(template)):
match (state, template[i]):
case (NotMatching(), '.'):
pass
case (NotMatching(), '?'):
options_in_other_branches += _match_one_template(template[i+1:], tuple(remaining_groups))
if not remaining_groups:
return options_in_other_branches
group, *remaining_groups = remaining_groups
state = Matching(1, group)
case (NotMatching(), '#'):
if not remaining_groups:
return options_in_other_branches
group, *remaining_groups = remaining_groups
state = Matching(1, group)
case (Matching(current_length, desired_length), '.') if current_length == desired_length:
state = NotMatching()
case (Matching(current_length, desired_length), '.') if current_length < desired_length:
return options_in_other_branches
case (Matching(current_length, desired_length), '?') if current_length == desired_length:
state = NotMatching()
case (Matching(current_length, desired_length), '?') if current_length < desired_length:
state = Matching(current_length + 1, desired_length)
case (Matching(current_length, desired_length), '#') if current_length < desired_length:
state = Matching(current_length + 1, desired_length)
case (Matching(current_length, desired_length), '#') if current_length == desired_length:
return options_in_other_branches
case _:
raise RuntimeError(f'unexpected {state=} with {template=} position {i} and {remaining_groups=}')
match state, remaining_groups:
case NotMatching(), []:
return options_in_other_branches + 1
case Matching(current, desired), [] if current == desired:
return options_in_other_branches + 1
case (NotMatching(), _) | (Matching(_, _), _):
return options_in_other_branches
raise RuntimeError(f'unexpected {state=} with {template=} at end of template and {remaining_groups=}')
def _unfold(template: str, groups: tuple[int, ...]) -> tuple[str, tuple[int, ...]]:
return '?'.join([template] * 5), groups * 5
class Day12(Solver):
def __init__(self):
super().__init__(12)
self.input: list[tuple[str, tuple[int]]] = []
def presolve(self, input: str):
lines = input.rstrip().split('\n')
for line in lines:
template, groups = line.split(' ')
self.input.append((template, tuple(int(group) for group in groups.split(','))))
def solve_first_star(self) -> int:
return sum(_match_one_template(template, groups) for template, groups in self.input)
def solve_second_star(self) -> int:
return sum(_match_one_template(*_unfold(template, groups)) for template, groups in self.input)
Took me way too long, but I'm happy with my solution now. I spent probably half an hour looking at my naive backtracking program churning away unsuccessfully before I thought of dynamic programming, meaning caching all intermediate results in a hashtable under their current state. The state is just the index into the spring array and the index into the range array, meaning there really can't be too many different entries. Doing so worked very well, solving part 2 in 4ms.
Adding the caching required me to switch from a loop to a recursive function, which turned out way easier. Why did no one tell me to just go recursive from the start?