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.
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.
case class Particle(x: Long, y: Long, z: Long, dx: Long, dy: Long, dz: Long)
def parseParticle(a: String): Option[Particle] = a match
case s"$x, $y, $z @ $dx, $dy, $dz" => Some(Particle(x.toLong, y.toLong, z.toLong, dx.trim.toLong, dy.trim.toLong, dz.trim.toLong))
case _ => None
def intersect(min: Double, max: Double)(p: Particle, q: Particle): Boolean =
val n = p.dx * q.y - p.y * p.dx - q.x * p.dy + p.x * p.dy
val d = p.dy * q.dx - p.dx * q.dy
if(d == 0) then false else
val k = n.toDouble/d
val k2 = (q.y + k * q.dy - p.y)/p.dy
val ix = q.x + k * q.dx
val iy = q.y + k * q.dy
k2 >= 0 && k >= 0 && min <= ix && ix <= max && min <= iy && iy <= max
def task1(a: List[String]): Long =
val particles = a.flatMap(parseParticle)
particles.combinations(2).count(l => intersect(2e14, 4e14)(l(0), l(1)))
import re as re2
from sympy import *
p, v, times, eqs = symbols('x y z'), symbols('dx dy dz'), [], []
def parse_eq(i: int, s: str):
parts = [int(p) for p in re2.split(r'[,\s@]+', s) if p.strip() != '']
time = Symbol(f't{i}')
times.append(time)
for rp, rv, hp, hv in zip(p, v, parts[:3], parts[3:]):
eqs.append(Eq(rp + time * rv, hp + time * hv))
# need 3 equations for result, everything after that just slows things down
neq = 3
with open('task1.txt', 'r') as fobj:
for i, s in zip(range(neq), fobj.readlines()):
parse_eq(i, s)
for sol in solve(eqs, list(p) + list(v) + times):
x, y, z, *_ = sol
print(x + y + z)
When doing functional programming, you can't really do loops (because of referential transparency, you can't update iterators or indices). However, recursion still works.
If you wonder why the function is a quadratic, I suggest drawing stuff on a piece of paper. Essentially, if there were no obstacles, the furthest reachable cells would form a large diamond, which is tiled by some copies of the diamond in the input and some copies of the corners. As these have constant size, and the large diamond will grow quadratically with steps, you need a quadratic number of copies (by drawing, you can see that if steps = k * width + width/2, then there are floor((2k + 1)^2/2) copies of the center diamond, and ceil((2k + 1)^2/2) copies of each corner around).
What complicates this somewhat is that you don't just have to be able to reach a square in the number of steps, but that the parity has to match: By a chessboard argument, you can see any given square only every second step, as each step you move from a black tile to a white one or vice versa. And the parities flip each time you cross a boundary, as the input width is odd. So actually you have to either just guess the coefficients of a quadratic, as you and @hades@lemm.ee did, or do some more working out by hand, which will give you the explicit form, which I did and can't really recommend.
Agreed, i get annoyed when I can't actually solve the problem. I would be ok if the inputs are trivial special cases, as long as feasible (but harder) generalized solutions still existed.
This has a line-second score of of about 100 (including the comments - I don't know what counts as code and what doesn't so I figured I just include everything); translating this 1:1 into c++ (https://pastebin.com/fPhfm7Bs) yields a line-second score of 2.9.
task2 is extremely disgusting code, but I was drawing an ugly picture of the situation and just wrote it down. Somehow, this worked first try.
import day10._
import day10.Dir._
import day11.Grid
extension (p: Pos) def parity = (p.x + p.y) % 2
def connect(p: Pos, d: Dir, g: Grid[Char]) =
val to = walk(p, d)
Option.when(g.inBounds(to) && g.inBounds(p) && g(to) != '#' && g(p) != '#')(DiEdge(p, to))
def parseGrid(a: List[List[Char]]) =
val g = Grid(a)
Graph() ++ g.indices.flatMap(p => Dir.all.flatMap(d => connect(p, d, g)))
def reachableIn(n: Int, g: Graph[Pos, DiEdge[Pos]], start: g.NodeT) =
@tailrec def go(q: List[(Int, g.NodeT)], depths: Map[Pos, Int]): Map[Pos, Int] =
q match
case (d, n) :: t =>
if depths.contains(n) then go(t, depths) else
val successors = n.outNeighbors.map(d + 1 -> _)
go(t ++ successors, depths + (n.outer -> d))
case _ =>
depths
go(List(0 -> start), Map()).filter((_, d) => d <= n).keys.toList
def compute(a: List[String], n: Int): Long =
val grid = Grid(a.map(_.toList))
val g = parseGrid(a.map(_.toList))
val start = g.get(grid.indexWhere(_ == 'S').head)
reachableIn(n, g, start).filter(_.parity == start.parity).size
def task1(a: List[String]): Long = compute(a, 64)
def task2(a: List[String]): Long =
// this only works for inputs where the following assertions holds
val steps = 26501365
assert((steps - a.size/2) % a.size == 0)
assert(steps % 2 == 1 && a.size % 2 == 1)
val d = steps/a.size
val k = (2 * d + 1)
val k1 = k*k/2
def sq(x: Long) = x * x
val grid = Grid(a.map(_.toList))
val g = parseGrid(a.map(_.toList))
val start = g.get(grid.indexWhere(_ == 'S').head)
val center = reachableIn(a.size/2, g, start)
// If you stare at the input enough, one can see that
// for certain values of steps, the total area is covered
// by some copies of the center diamond, and some copies
// of the remaining triangle shapes.
//
// In some repetitions, the parity of the location of S is
// the same as the parity of the original S.
// d0 counts the cells reachable in a center diamond where
// this holds, dn0 counts the cells reachable in a center diamond
// where the parity is flipped.
// The triangular shapes are counted by dr and dnr, respectively.
//
// The weird naming scheme is taken directly from the weird diagram
// I drew in order to avoid further confusing myself.
val d0 = center.count(_.parity != start.parity)
val dr = g.nodes.count(_.parity != start.parity) - d0
val dn0 = center.size - d0
val dnr = dr + d0 - dn0
// these are the counts of how often each type of area appears
val r = sq(2 * d + 1) / 2
val (rplus, rminus) = (r/2, r/2)
val z = sq(2 * d + 1) / 2 + 1
val zplus = sq(1 + 2*(d/2))
val zminus = z - zplus
// calc result
zplus * d0 + zminus * dn0 + rplus * dr + rminus * dnr
Ok so this is a little weird. My code for task1 is attached to this comment, but I actually solved task2 by hand.
After checking that bruteforce indeed takes longer than a second, I plotted the graph just to see what was going on, and you can immediately tell that the result is the least common multiple of four numbers, which can easily be obtained by running task1 with a debugger, and maybe read directly from the graph as well.
I also pre-broke my include statements, so hopefully the XSS protection isn't completely removing them again.
Learning about scala-graph yesterday seems to have paid off already. This explicitly constructs the entire graph of allowed moves, and then uses a naive dijkstra run. This works, and I don't have to write a lot of code, but it is fairly inefficient.
import day10._
import day10.Dir._
import day11.Grid
// standing on cell p, having entered from d
case class Node(p: Pos, d: Dir)
def connect(p: Pos, d: Dir, g: Grid[Int], dists: Range) =
val from = Seq(-1, 1).map(i => Dir.from(d.n + i)).map(Node(p, _))
val ends = List.iterate(p, dists.last + 1)(walk(_, d)).filter(g.inBounds)
val costs = ends.drop(1).scanLeft(0)(_ + g(_))
from.flatMap(f => ends.zip(costs).drop(dists.start).map((dest, c) => WDiEdge(f, Node(dest, d), c)))
def parseGrid(a: List[List[Char]], dists: Range) =
val g = Grid(a.map(_.map(_.getNumericValue)))
Graph() ++ g.indices.flatMap(p => Dir.all.flatMap(d => connect(p, d, g, dists)))
def compute(a: List[String], dists: Range): Long =
val g = parseGrid(a.map(_.toList), dists)
val source = Node(Pos(-1, -1), Right)
val sink = Node(Pos(-2, -2), Right)
val start = Seq(Down, Right).map(d => Node(Pos(0, 0), d)).map(WDiEdge(source, _, 0))
val end = Seq(Down, Right).map(d => Node(Pos(a(0).size - 1, a.size - 1), d)).map(WDiEdge(_, sink, 0))
val g2 = g ++ start ++ end
g2.get(source).shortestPathTo(g2.get(sink)).map(_.weight).getOrElse(-1.0).toLong
def task1(a: List[String]): Long = compute(a, 1 to 3)
def task2(a: List[String]): Long = compute(a, 4 to 10)
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.
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 + 1is 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), whereai + b(bi)may already equala.size(in the case where the block ends exactly at the end ofa). The+ 1in 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 ata.size, but then, for e.g.b = [2, 3], we would consider...#####.a valid placement.Let me know if there are still things unclear :)
Scala3
all done!
Scala3, Sympy
When doing functional programming, you can't really do loops (because of referential transparency, you can't update iterators or indices). However, recursion still works.
Scala3
Scala3
Not much to say about this, very straightforward implementation that was still fast enough
If you wonder why the function is a quadratic, I suggest drawing stuff on a piece of paper. Essentially, if there were no obstacles, the furthest reachable cells would form a large diamond, which is tiled by some copies of the diamond in the input and some copies of the corners. As these have constant size, and the large diamond will grow quadratically with steps, you need a quadratic number of copies (by drawing, you can see that if
steps = k * width + width/2, then there arefloor((2k + 1)^2/2)copies of the center diamond, andceil((2k + 1)^2/2)copies of each corner around).What complicates this somewhat is that you don't just have to be able to reach a square in the number of steps, but that the parity has to match: By a chessboard argument, you can see any given square only every second step, as each step you move from a black tile to a white one or vice versa. And the parities flip each time you cross a boundary, as the input width is odd. So actually you have to either just guess the coefficients of a quadratic, as you and @hades@lemm.ee did, or do some more working out by hand, which will give you the explicit form, which I did and can't really recommend.
Agreed, i get annoyed when I can't actually solve the problem. I would be ok if the inputs are trivial special cases, as long as feasible (but harder) generalized solutions still existed.
This has a line-second score of of about 100 (including the comments - I don't know what counts as code and what doesn't so I figured I just include everything); translating this 1:1 into c++ (https://pastebin.com/fPhfm7Bs) yields a line-second score of 2.9.
Scala3
task2 is extremely disgusting code, but I was drawing an ugly picture of the situation and just wrote it down. Somehow, this worked first try.
C++, kind of
Ok so this is a little weird. My code for task1 is attached to this comment, but I actually solved task2 by hand. After checking that bruteforce indeed takes longer than a second, I plotted the graph just to see what was going on, and you can immediately tell that the result is the least common multiple of four numbers, which can easily be obtained by running task1 with a debugger, and maybe read directly from the graph as well. I also pre-broke my include statements, so hopefully the XSS protection isn't completely removing them again.
My graph: https://files.catbox.moe/1u4daw.png
blue is the broadcaster/button, yellows are flipflops, purples are nand gates and green is the output gate.
Also I abandoned scala again, because there is so much state modification going on.
Scala3
looks like some broken XSS protection is killing the includes, can't really fix that
C++
No scala today
Scala3
Learning about scala-graph yesterday seems to have paid off already. This explicitly constructs the entire graph of allowed moves, and then uses a naive dijkstra run. This works, and I don't have to write a lot of code, but it is fairly inefficient.
Scala3
This could be much more efficient (and quite a bit shorter), but I wanted to try out the scala-graph library (https://www.scala-graph.org)
Scala3
Scala3