Day 7: Bridge Repair

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

3 points

Factor

spoiler
TUPLE: equation value numbers ;
C: <equation> equation

: get-input ( -- equations )
  "vocab:aoc-2024/07/input.txt" utf8 file-lines [
    split-words unclip but-last string>number
    swap [ string>number ] map <equation>
  ] map ;

: possible-quotations ( funcs numbers -- quots )
  dup length 1 -
  swapd all-selections
  [ unclip swap ] dip
  [ zip concat ] with map
  swap '[ _ prefix >quotation ] map ;

: possibly-true? ( funcs equation -- ? )
  [ numbers>> possible-quotations ] [ value>> ] bi
  '[ call( -- n ) _ = ] any? ;

: solve ( funcs -- n )
  get-input
  [ possibly-true? ] with filter
  [ value>> ] map-sum ;

: part1 ( -- n )
  { + * } solve ;

: _|| ( m n -- mn )
  [ number>string ] bi@ append string>number ;

: part2 ( -- n )
  { + * _|| } solve ;
permalink
report
reply
1 point
*

Slow and dumb gets it done! I may revisit this when I give up on future days.

permalink
report
parent
reply
4 points
*

Haskell

A surprisingly gentle one for the weekend! Avoiding string operations for concatenate got the runtime down below one second on my machine.

import Control.Arrow
import Control.Monad
import Data.List
import Data.Maybe

readInput :: String -> [(Int, [Int])]
readInput = lines >>> map (break (== ':') >>> (read *** map read . words . tail))

equatable :: [Int -> Int -> Int] -> (Int, [Int]) -> Bool
equatable ops (x, y : ys) = elem x $ foldM apply y ys
  where
    apply a y = (\op -> a `op` y) <$> ops

concatenate :: Int -> Int -> Int
concatenate x y = x * mag y + y
  where
    mag z = fromJust $ find (> z) $ iterate (* 10) 10

main = do
  input <- readInput <$> readFile "input07"
  mapM_
    (print . sum . map fst . (`filter` input) . equatable)
    [ [(+), (*)],
      [(+), (*), concatenate]
    ]
permalink
report
reply
3 points

Love the fold on the list monad to apply the operations.

permalink
report
parent
reply
2 points

I wanted to this the way yo did, by repeatedly applying functions, but I didn’t dare to because I like to mess up and spend some minutes debugging signatures, may I ask what your IDE setup is for the LSP-Hints with Haskell?
Setting up on my PC was a little bit of a pain because it needed matching ghc and ghcide versions, so I hadn’t bothered doing it on my Laptop yet.

permalink
report
parent
reply
3 points

I use neovim with haskell-tools.nvim plugin. For ghc, haskell-language-server and others I use nix which, among other benefits makes my development environment reproducible and all haskellPackages are built on the same version so there are no missmatches.

But, as much as I love nix, there are probably easier ways to setup your environment.

permalink
report
parent
reply
2 points

I just checked and I have haskell-tools.nvim on my PC but it somehow crashes the default config of the autocompletion for me, which I am too inexperienced to debug. I’ll try it nonetheless, since I don’t have autocompletion on the laptop anyways, thank you for the suggestion!

permalink
report
parent
reply
2 points

Ah, well, I have a bit of a weird setup. GHC is 9.8.4, built from git. I’m using HLS version 2.9.0.1 (again built from git) under Emacs with the LSP and flycheck packages. There are probably much easier ways of getting it to work :)

permalink
report
parent
reply
2 points

I envy emacs for all of its modes, but I don’t think I’m relearning the little I know about vi. Thank you for the answer on the versions and building!

permalink
report
parent
reply
2 points
*

Since all operations increase the accumulator, I tried putting a guard (a <= x) in apply, but it doesn’t actually help all that much (0.65s -> 0.43s).

permalink
report
parent
reply
2 points
*

0.65 -> 0.43 sounds pretty strong, isn’t that a one-fourth speedup?

Edit: I was able to achieve a 30% speed improvement using this on my solution

permalink
report
parent
reply
2 points

It’s not insignificant, sure, but I’d prefer 10x faster :D

Plus I’m not sure it’s worth the loss of generality and readability. It is tempting to spend hours chasing this kind of optimization though!

permalink
report
parent
reply
2 points

C#

public class Day07 : Solver
{
  private ImmutableList<(long, ImmutableList<long>)> equations;

  public void Presolve(string input) {
    equations = input.Trim().Split("\n")
      .Select(line => line.Split(": "))
      .Select(split => (long.Parse(split[0]), split[1].Split(" ").Select(long.Parse).ToImmutableList()))
      .ToImmutableList();
  }

  private bool TrySolveWithConcat(long lhs, long head, ImmutableList<long> tail) {
    var lhs_string = lhs.ToString();
    var head_string = head.ToString();
    return lhs_string.Length > head_string.Length &&
      lhs_string.EndsWith(head_string) &&
      SolveEquation(long.Parse(lhs_string.Substring(0, lhs_string.Length - head_string.Length)), tail, true);
  }

  private bool SolveEquation(long lhs, ImmutableList<long> rhs, bool with_concat = false) {
    if (rhs.Count == 1) return lhs == rhs[0];
    long head = rhs[rhs.Count - 1];
    var tail = rhs.GetRange(0, rhs.Count - 1);
    return (SolveEquation(lhs - head, tail, with_concat))
      || (lhs % head == 0) && SolveEquation(lhs / head, tail, with_concat)
      || with_concat && TrySolveWithConcat(lhs, head, tail);
  }

  public string SolveFirst() => equations
    .Where(eq => SolveEquation(eq.Item1, eq.Item2))
    .Select(eq => eq.Item1)
    .Sum().ToString();
  public string SolveSecond() => equations
    .Where(eq => SolveEquation(eq.Item1, eq.Item2, true))
    .Select(eq => eq.Item1)
    .Sum().ToString();
}
permalink
report
reply
2 points
*

python

45s on my machine for first shot, trying to break my will to brute force πŸ˜…. I’ll try improving on it in a bit after I smoke another bowl and grab another drink.

solution
import itertools
import re
import aoc

def ltr(e):
    r = int(e[0])
    for i in range(1, len(e), 2):
        o = e[i]
        n = int(e[i + 1])
        if o == '+':
            r += n
        elif o == '*':
            r *= n
        elif o == '||':
            r = int(f"{r}{n}")
    return r

def pl(l, os):
    d = [int(x) for x in re.findall(r'\d+', l)]
    t, ns = d[0], d[1:]
    ops = list(itertools.product(os, repeat=len(ns) - 1))
    for o in ops:
        e = str(ns[0])
        for i, op in enumerate(o):
            e += f" {op} {ns[i + 1]}"
        r = ltr(e.split())
        if r == t:
            return r
    return 0

def one():
    lines = aoc.get_lines(7)
    acc = 0
    for l in lines:
        acc += pl(l, ['+', '*'])
    print(acc)

def two():
    lines = aoc.get_lines(7)
    acc = 0
    for l in lines:
        acc += pl(l, ['+', '*', '||'])
    print(acc)

one()
two()
permalink
report
reply
1 point

What a horrible way to name variables

permalink
report
parent
reply
1 point

a e o, Killer Tofu. That’s all I can think of reading this code.

permalink
report
parent
reply
1 point
*

It’s not a long lived project, it’s a puzzle, and once solved never needs to run again. My objective here is to get the correct answer, not win a style contest.

Can you provide a link to your solution? I’d like to check it out.

permalink
report
parent
reply
1 point
*

My initial comment was a bit harsh, I’m sorry for that. It was meant to be a bit of a joke. Anyway here’s my code. Do note that I don’t do the challenges timed so I have a bit more time to name my variables accordingly. Takes 35 seconds to run on a pc with a AMD Ryzen 5 5600

import sys
from tqdm import tqdm


input = sys.stdin.read()

def all_operator_permutations(operator_count):
    if operator_count == 0:
        return [[]]

    smaller_permutations = all_operator_permutations(operator_count-1)
    return [
            *[['+', *ops] for ops in smaller_permutations],
            *[['*', *ops] for ops in smaller_permutations],
            *[['||', *ops] for ops in smaller_permutations],
            ]

def test_operators(ops, values):
    res = values.pop(0)
    for op in ops:
        match op:
            case '*':
                res *= values.pop(0)
            case '+':
                res += values.pop(0)
            case '||':
                res = int(f"{res}{values.pop(0)}")
    return res


total_calibration_result = 0

for line in tqdm(input.splitlines()[:]):
    target, *tail = line.split(':')
    target = int(target)
    values = [int(val) for val in tail[0].split()]

    all_perms = all_operator_permutations(len(values) - 1)
    ops = all_perms.pop()
    while True:
        res = test_operators(ops, values.copy())
        if res == target:
            total_calibration_result += target
            break
        if not all_perms:
            break
        ops = all_perms.pop()

print(total_calibration_result)
permalink
report
parent
reply
2 points
*

Made a couple of attempts to munge the input data into some kind of binary search tree, lost some time to that, then threw my hands into the air and did a more naΓ―ve sort-of breadth-first search instead. Which turned out to be better for part 2 anyway.
Also, maths. Runs in just over a hundred milliseconds when using AsParallel, around half a second without.

C#
List<(long, int[])> data = new List<(long, int[])>();

public void Input(IEnumerable<string> lines)
{
  foreach (var line in lines)
  {
    var parts = line.Split(':', StringSplitOptions.TrimEntries);

    data.Add((long.Parse(parts.First()), parts.Last().Split(' ').Select(int.Parse).ToArray()));
  }
}

public void Part1()
{
  var correct = data.Where(kv => CalcPart(kv.Item1, kv.Item2)).Select(kv => kv.Item1).Sum();

  Console.WriteLine($"Correct: {correct}");
}
public void Part2()
{
  var correct = data.AsParallel().Where(kv => CalcPart2(kv.Item1, kv.Item2)).Select(kv => kv.Item1).Sum();

  Console.WriteLine($"Correct: {correct}");
}

public bool CalcPart(long res, Span<int> num, long carried = 0)
{
  var next = num[0];
  if (num.Length == 1)
    return res == carried + next || res == carried * next;
  return CalcPart(res, num.Slice(1), carried + next) || CalcPart(res, num.Slice(1), carried * next);
}

public bool CalcPart2(long res, Span<int> num, long carried = 0)
{
  var next = num[0];
  // Get the 10 logarithm for the next number, expand the carried value by 10^<next 10log + 1>, add the two together
  // For 123 || 45
  // 45 β‡’ 10log(45) + 1 == 2
  // 123 * 10^2 + 45 == 12345
  long combined = carried * (long)Math.Pow(10, Math.Floor(Math.Log10(next) + 1)) + next;
  if (num.Length == 1)
    return res == carried + next || res == carried * next || res == combined;
  return CalcPart2(res, num.Slice(1), carried + next) || CalcPart2(res, num.Slice(1), carried * next) || CalcPart2(res, num.Slice(1), combined);
}
permalink
report
reply
1 point

you meant depth first, right? since you’re using recursion

permalink
report
parent
reply
1 point

That is true, I’ve evidently not had enough coffee yet this morning.

permalink
report
parent
reply

Advent Of Code

!advent_of_code@programming.dev

Create post

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.

AoC 2024

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

Rules/Guidelines

  • Follow the programming.dev instance rules
  • Keep all content related to advent of code in some way
  • If what youre posting relates to a day, put in brackets the year and then day number in front of the post title (e.g. [2024 Day 10])
  • When an event is running, keep solutions in the solution megathread to avoid the community getting spammed with posts

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

Community stats

  • 482

    Monthly active users

  • 108

    Posts

  • 1.1K

    Comments