Day 14 Mathy solution
This commit is contained in:
@@ -6,3 +6,8 @@ def gcd(a: Int, b: Int): Int =
|
|||||||
extension [A](xs: Seq[A])
|
extension [A](xs: Seq[A])
|
||||||
def pairs: Iterator[(A, A)] =
|
def pairs: Iterator[(A, A)] =
|
||||||
xs.combinations(2).map(xs => (xs(0), xs(1)))
|
xs.combinations(2).map(xs => (xs(0), xs(1)))
|
||||||
|
|
||||||
|
def eea(a: Int, b: Int): (Int, Int, Int) =
|
||||||
|
if b == 0 then return (a, 1, 0)
|
||||||
|
val (d, x, y) = eea(b, a % b)
|
||||||
|
(d, y, x - y * (a / b))
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
package dev.ctsk.aoc.days
|
package dev.ctsk.aoc.days
|
||||||
|
|
||||||
import dev.ctsk.aoc.*
|
import dev.ctsk.aoc._
|
||||||
import os.ReadablePath
|
import os.ReadablePath
|
||||||
import scala.util.boundary
|
|
||||||
import scala.util.boundary.break
|
def mu(arr: Seq[Int]) = arr.sum * 1.0 / arr.length
|
||||||
|
def va(arr: Seq[Int]) = { val m = mu(arr); arr.map(v => (v - m) * (v - m)).sum }
|
||||||
|
|
||||||
object Day14 extends Solver(14):
|
object Day14 extends Solver(14):
|
||||||
private val Y = 101
|
private val Y = 101
|
||||||
@@ -22,27 +23,18 @@ object Day14 extends Solver(14):
|
|||||||
ul * ur * dl * dr
|
ul * ur * dl * dr
|
||||||
|
|
||||||
def part2(robots: Array[(Point, Point)]): Int =
|
def part2(robots: Array[(Point, Point)]): Int =
|
||||||
val hist = Array.fill(X, Y)(0)
|
val xo = (0 to 103).minBy(t => va(robots.map(go(_, t).x).take(50)))
|
||||||
def isTree(t: Int): Boolean =
|
val yo = (0 to 103).minBy(t => va(robots.map(go(_, t).y).take(50)))
|
||||||
boundary:
|
val (_, iX, iY) = eea(X, Y)
|
||||||
for i <- robots.indices
|
(xo * iY * Y + yo * iX * X) % (X * Y)
|
||||||
do
|
|
||||||
val dst = go(robots(i), t)
|
|
||||||
if hist(dst.x)(dst.y) == t then break(false)
|
|
||||||
hist(dst.x)(dst.y) = t
|
|
||||||
break(true)
|
|
||||||
|
|
||||||
(1 to X * Y).find(isTree).get
|
|
||||||
|
|
||||||
override def run(input: ReadablePath): (Timings, Solution) =
|
override def run(input: ReadablePath): (Timings, Solution) =
|
||||||
val (pre_time, robots) = timed {
|
def parse(line: String): (Point, Point) =
|
||||||
os.read
|
longs(line) match {
|
||||||
.lines(input)
|
case Vector(y, x, dy, dx) => (Point.of(x, y), Point.of(dx, dy))
|
||||||
.map(longs)
|
|
||||||
.map { case Vector(y, x, dy, dx) => (Point.of(x, y), Point.of(dx, dy)) }
|
|
||||||
.toArray
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
val (pre_time, robots) = timed { os.read.lines(input).map(parse).toArray }
|
||||||
val (p1_time, p1) = timed { part1(robots) }
|
val (p1_time, p1) = timed { part1(robots) }
|
||||||
val (p2_time, p2) = timed { part2(robots) }
|
val (p2_time, p2) = timed { part2(robots) }
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user