cvttsd2si

joined 10 months ago
[–] [email protected] 1 points 9 months ago

Scala3

def compute(a: List[String], growth: Long): Long =
    val gaps = Seq(a.map(_.toList), a.transpose).map(_.zipWithIndex.filter((d, i) => d.forall(_ == '.')).map(_._2).toSet)
    val stars = for y <- a.indices; x <- a(y).indices if a(y)(x) == '#' yield List(x, y)

    def dist(gaps: Set[Int], a: Int, b: Int): Long = 
        val i = math.min(a, b) until math.max(a, b)
        i.size.toLong + (growth - 1)*i.toSet.intersect(gaps).size.toLong

    (for Seq(p, q) <- stars.combinations(2); m <- gaps.lazyZip(p).lazyZip(q).map(dist) yield m).sum

def task1(a: List[String]): Long = compute(a, 2)
def task2(a: List[String]): Long = compute(a, 1_000_000)
[–] [email protected] 3 points 9 months ago* (last edited 9 months ago)

Scala3

def diffs(a: Seq[Long]): List[Long] =
    a.drop(1).zip(a).map(_ - _).toList

def predictNext(a: Seq[Long], combine: (Seq[Long], Long) => Long): Long =
    if a.forall(_ == 0) then 0 else combine(a, predictNext(diffs(a), combine))

def predictAllNexts(a: List[String], combine: (Seq[Long], Long) => Long): Long = 
    a.map(l => predictNext(l.split(raw"\s+").map(_.toLong), combine)).sum

def task1(a: List[String]): Long = predictAllNexts(a, _.last + _)
def task2(a: List[String]): Long = predictAllNexts(a, _.head - _)
[–] [email protected] 2 points 10 months ago (1 children)

re [^1]: yeah, but that may explode the runtime again. Do you have any idea if this is possible to solve without brute forcing the combinations?

[–] [email protected] 6 points 10 months ago* (last edited 10 months ago) (1 children)

I can prove the opposite for you. The assumption that Gobbel2000 describes is wrong in general. For example, take

L

A -> B, X
B -> C, X
C -> Z, X
Z -> C, X
X -> X, X

the first Z is reached after 3 steps, but then every cycle only takes 2 steps.

The matches are still at consistent intervals, but you can easily find a counterexample for that as well:

L

A -> 1Z, X
1Z -> 2Z, X
2Z -> A, X
X -> X, X

now the intervals will be 2, 1, 2, 1, ...

However, it is easy to prove that there will be a loop of finite length, and that the intervals will behave somewhat nicely:

Identify a "position" by a node you are at, and your current index in the LRL instruction sequence. If you ever repeat a position P, you will repeat the exact path away from the position you took the last time, and the last time you later reached P, so you will keep reaching P again and again. There are finitely many positions, so you can't keep not repeating any forever, you will run out.

Walking in circles along this loop you eventually find yourself in, the intervals between Zs you see will definitely be a repeating sequence (as you will keep seeing not just same-length intervals, but in fact the exact same paths between Zs).

So in total, you will see some finite list of prefix-intervals, and then a repeating cycle of loop-intervals. I have no idea if this can be exploited to compute the answer efficiently, but see my solution-comment for something that only assumes that only one Z will be encountered each cycle.

[–] [email protected] 5 points 10 months ago* (last edited 10 months ago)

Scala3

this is still not 100% general, as it assumes there is only one Z-node along the path for each start. But it doesn't assume anything else, I think. If you brute force combinations of entries of the zs-arrays, this assumption can be trivially removed, but if multiple paths see lots of Z-nodes, then the runtime will grow exponentially. I don't know if it's possible to do this any faster.

def parse(a: List[String]): (List[Char], Map[String, Map[Char, String]]) =
    def parseNodes(n: List[String]) =
        n.flatMap{case s"$from = ($l, $r)" => Some(from -> Map('L'->l, 'R'->r)); case _ => None}.toMap
    a match{case instr::""::nodes => ( instr.toList, parseNodes(nodes) ); case _ => (List(), Map())}

def task1(a: List[String]): Long =
    val (instr, nodes) = parse(a)
    def go(i: Stream[Char], pos: String, n: Long): Long =
        if pos != "ZZZ" then go(i.tail, nodes(pos)(i.head), n+1) else n
    go(instr.cycle, "AAA", 0)

// ok so i originally thought this was going to be difficult, so
// we parse a lot of info we won't use
case class PathInfo(zs: List[Long], loopFrom: Long, loopTo: Long):
    def stride: Long = loopTo - loopFrom

type Cycle = Long

def getInfo(instr: List[Char], isEnd: String => Boolean, map: Map[String, Map[Char, String]], start: String): PathInfo =
    def go(i: Cycle, pos: String, is: List[Char], seen: Map[(Long, String), Cycle], acc: List[Long]): PathInfo =
        val current: (Long, String) = (is.size % instr.size, pos)
        val nis = if is.isEmpty then instr else is
        val nacc = if isEnd(pos) then i::acc else acc
        seen.get(current) match
            case Some(l) => PathInfo(acc, l, i)
            case _ => go(i + 1, map(pos)(nis.head), nis.tail, seen + (current -> i), nacc)
    go(0, start, instr, Map(), List())

// turns out we don't need to check all the different positions
// in each cycle where we are on a Z position, as a) every start
// walks into unique cycles with b) exactly one Z position,
// and c) the length of the cycle is equivalent to the steps to first
// encounter a Z (so a->b->c->Z->c->Z->... is already more complicated, 
// as the cycle length is 2 but the first encounter is after 3 steps)

// anyway let's do some math

// this is stolen code
def gcd(a: Long, b: Long): Long =
    if(b ==0) a else gcd(b, a%b)

def primePowers(x: Long): Map[Long, Long] =
    // for each prime p for which p^k divides x: p->p^k
    def go(r: Long, t: Long, acc: Map[Long, Long]): Map[Long, Long] =
        if r == 1 then acc else
            if r % t == 0 then
                go(r/t, t, acc + (t -> acc.getOrElse(t, 1L)*t))
            else
                go(r, t+1, acc)
    go(x, 2, Map())

// this algorithm is stolen, but I scalafied the impl
def vanillaCRT(congruences: Map[Long, Long]): Long = 
    val N = congruences.keys.product
    val x = congruences.map((n, y) => y*(N/n)*((N/n) % n)).sum
    if x <= 0 then x + N else x

def generalizedHardcoreCRTThatCouldHaveBeenAnLCMBecauseTheInputIsVeryConvenientlyTrivialButWeWantToDoThisRight(ys: List[Long], xs: List[Long]): Option[Long] =
    // finds the smallest k s.t. k === y_i  (mod x_i) for each i
    // even when stuff is not nice

    // pre-check if everything is sufficiently coprime
    // https://math.stackexchange.com/questions/1644677/what-to-do-if-the-modulus-is-not-coprime-in-the-chinese-remainder-theorem
    val vars = for
        ((y1, n1), i1) <- ys.zip(xs).zipWithIndex
        ((y2, n2), i2) <- ys.zip(xs).zipWithIndex
        if i2 > i1
    yield 
        val g = gcd(n1, n2)
        y1 % g == y2 % g
    
    if !vars.forall(a => a) then
        None
    else
        // we need to split k === y (mod mn) into k === y (mod m) and k === y (mod n) for m, n coprime
        val congruences = for
            (x, y) <- xs.zip(ys)
            (p, pl) <- primePowers(x)
        yield
            p -> (y % pl -> pl)
        
        // now we eliminate redundant congruences
        // since our input is trivial, this is essentially
        // the step in which we solve the task by 
        // accidentaly computing an lcm
        val r = congruences.groupMap(_._1)(_._2).mapValues(l => l.map(_._2).max -> l.head._1).values.toMap
        
        // ok now we meet the preconditions
        // for doing this
        Some(vanillaCRT(r))

def task2(a: List[String]): Long =
    val (instr, nodes) = parse(a)
    val infos = nodes.keySet.filter(_.endsWith("A")).map(s => getInfo(instr, _.endsWith("Z"), nodes, s))
    generalizedHardcoreCRTThatCouldHaveBeenAnLCMBecauseTheInputIsVeryConvenientlyTrivialButWeWantToDoThisRight(
        infos.map(_.zs.head).toList, infos.map(_.stride).toList
    ).getOrElse(0)

@main def main: Unit =
  val data = readlines("/home/tim/test/aoc23/aoc23/inputs/day8/task1.txt")
  for f <- List(
      task1,
      task2,
    ).map(_ andThen println)
  do f(data)
[–] [email protected] 3 points 10 months ago

Scala3

val tiers = List(List(1, 1, 1, 1, 1), List(1, 1, 1, 2), List(1, 2, 2), List(1, 1, 3), List(2, 3), List(1, 4), List(5))
val cards = List('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A')

def cardValue(base: Long, a: List[Char], cards: List[Char]): Long =
    a.foldLeft(base)(cards.size * _ + cards.indexOf(_))

def hand(a: List[Char]): List[Int] =
    a.groupMapReduce(s => s)(_ => 1)(_ + _).values.toList.sorted

def power(a: List[Char]): Long =
  cardValue(tiers.indexOf(hand(a)), a, cards)

def power3(a: List[Char]): Long = 
  val x = hand(a.filter(_ != 'J'))
  val t = tiers.lastIndexWhere(x.zipAll(_, 0, 0).forall(_ <= _))
  cardValue(t, a, 'J'::cards)

def win(a: List[String], pow: List[Char] => Long) =
    a.flatMap{case s"$hand $bid" => Some((pow(hand.toList), bid.toLong)); case _ => None}
        .sorted.map(_._2).zipWithIndex.map(_ * _.+(1)).sum

def task1(a: List[String]): Long = win(a, power)
def task2(a: List[String]): Long = win(a, power3)
[–] [email protected] 3 points 10 months ago* (last edited 10 months ago)

Scala3

// math.floor(i) == i if i.isWhole, but we want i-1
def hardFloor(d: Double): Long = (math.floor(math.nextAfter(d, Double.NegativeInfinity))).toLong
def hardCeil(d: Double): Long = (math.ceil(math.nextAfter(d, Double.PositiveInfinity))).toLong

def wins(t: Long, d: Long): Long =
    val det = math.sqrt(t*t/4.0 - d)
    val high = hardFloor(t/2.0 + det)
    val low = hardCeil(t/2.0 - det)
    (low to high).size

def task1(a: List[String]): Long = 
    def readLongs(s: String) = s.split(raw"\s+").drop(1).map(_.toLong)
    a match
        case List(s"Time: $time", s"Distance: $dist") => readLongs(time).zip(readLongs(dist)).map(wins).product
        case _ => 0L

def task2(a: List[String]): Long =
    def readLong(s: String) = s.replaceAll(raw"\s+", "").toLong
    a match
        case List(s"Time: $time", s"Distance: $dist") => wins(readLong(time), readLong(dist))
        case _ => 0L
[–] [email protected] 3 points 10 months ago

Scala3

kind of convoluted, but purely functional

import scala.collection.immutable.NumericRange.Exclusive
import math.max
import math.min

extension [A] (l: List[A])
  def chunk(pred: A => Boolean): List[List[A]] =
    def go(l: List[A], partial_acc: List[A], acc: List[List[A]]): List[List[A]] =
      l match
        case (h :: t) if pred(h) => go(t, List(), partial_acc.reverse :: acc)
        case (h :: t) => go(t, h :: partial_acc, acc)
        case _ => partial_acc.reverse :: acc
    
    go(l, List(), List()).reverse

type R = Exclusive[Long]

def intersectTranslate(r: R, c: R, t: Long): R =
    (t + max(r.start, c.start) - c.start) until (t + min(r.end, c.end) - c.start)

case class MappingEntry(from: R, to: Long)
case class Mapping(entries: List[MappingEntry], produces: String):
    def resolveRange(in: R): List[R] =
        entries.map(e => intersectTranslate(in, e.from, e.to)).filter(!_.isEmpty)

def completeEntries(a: List[MappingEntry]): List[MappingEntry] = 
    a ++ ((0L until 0L) +: a.map(_.from).sorted :+ (Long.MaxValue until Long.MaxValue)).sliding(2).flatMap{ case List(a, b) => Some(MappingEntry(a.end until b.start, a.end)); case _ => None}.toList

def parse(a: List[String], init: List[Long] => List[R]): (List[R], Map[String, Mapping]) =
    def parseEntry(s: String): MappingEntry =
        s match
            case s"$end $start $range" => MappingEntry(start.toLong until start.toLong + range.toLong, end.toLong)

    a.chunk(_ == "") match
        case List(s"seeds: $seeds") :: maps => 
            init(seeds.split(raw"\s+").map(_.toLong).toList) -> (maps.flatMap{ case s"$from-to-$to map:" :: entries => Some(from -> Mapping(completeEntries(entries.map(parseEntry)), to)); case _ => None }).toMap
        case _ => (List(), Map()).ensuring(false)

def singletons(a: List[Long]): List[R] = a.map(s => s until s + 1)
def paired(a: List[Long]): List[R] = a.grouped(2).flatMap{ case List(x, y) => Some(x until x+y); case _ => None }.toList

def chase(d: (List[R], Map[String, Mapping]), initial: String, target: String) =
    val (init, m) = d
    def go(a: List[R], s: String): List[R] =
        if trace(s) == target then a else
            val x = m(s)
            go(a.flatMap(x.resolveRange), x.produces)
    go(trace(init), initial)

def task1(a: List[String]): Long = 
    chase(parse(a, singletons), "seed", "location").min.start

def task2(a: List[String]): Long =
    chase(parse(a, paired), "seed", "location").min.start
view more: ‹ prev next ›