this post was submitted on 07 Dec 2024
22 points (89.3% liked)

Advent Of Code

987 readers
8 users here now

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

Relevant Communities

Relevant Links

Credits

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

console.log('Hello World')

founded 1 year ago
MODERATORS
 

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

you are viewing a single comment's thread
view the rest of the comments
[โ€“] hades@lemm.ee 2 points 3 weeks ago

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();
}