Day 5: Print Queue

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

6 points
*

Nim

Solution: sort numbers using custom rules and compare if sorted == original. Part 2 is trivial.
Runtime for both parts: 1.05 ms

proc parseRules(input: string): Table[int, seq[int]] =
  for line in input.splitLines():
    let pair = line.split('|')
    let (a, b) = (pair[0].parseInt, pair[1].parseInt)
    discard result.hasKeyOrPut(a, newSeq[int]())
    result[a].add b

proc solve(input: string): AOCSolution[int, int] =
  let chunks = input.split("\n\n")
  let later = parseRules(chunks[0])
  for line in chunks[1].splitLines():
    let numbers = line.split(',').map(parseInt)
    let sorted = numbers.sorted(cmp =
      proc(a,b: int): int =
        if a in later and b in later[a]: -1
        elif b in later and a in later[b]: 1
        else: 0
    )
    if numbers == sorted:
      result.part1 += numbers[numbers.len div 2]
    else:
      result.part2 += sorted[sorted.len div 2]

Codeberg repo

permalink
report
reply
1 point

Nice, compact and easy to follow. The implicit result object reminds me of Visual Basic.

permalink
report
parent
reply
5 points
*

Kotlin

Took me a while to figure out how to sort according to the rules. 🤯

fun part1(input: String): Int {
    val (rules, listOfNumbers) = parse(input)
    return listOfNumbers
        .filter { numbers -> numbers == sort(numbers, rules) }
        .sumOf { numbers -> numbers[numbers.size / 2] }
}

fun part2(input: String): Int {
    val (rules, listOfNumbers) = parse(input)
    return listOfNumbers
        .filterNot { numbers -> numbers == sort(numbers, rules) }
        .map { numbers -> sort(numbers, rules) }
        .sumOf { numbers -> numbers[numbers.size / 2] }
}

private fun sort(numbers: List<Int>, rules: List<Pair<Int, Int>>): List<Int> {
    return numbers.sortedWith { a, b -> if (rules.contains(a to b)) -1 else 1 }
}

private fun parse(input: String): Pair<List<Pair<Int, Int>>, List<List<Int>>> {
    val (rulesSection, numbersSection) = input.split("\n\n")
    val rules = rulesSection.lines()
        .mapNotNull { line -> """(\d{2})\|(\d{2})""".toRegex().matchEntire(line) }
        .map { match -> match.groups[1]?.value?.toInt()!! to match.groups[2]?.value?.toInt()!! }
    val numbers = numbersSection.lines().map { line -> line.split(',').map { it.toInt() } }
    return rules to numbers
}
permalink
report
reply
2 points

I like how clean this is

permalink
report
parent
reply
1 point

I guess adding type aliases and removing the regex from parser makes it a bit more readable.

typealias Rule = Pair<Int, Int>
typealias PageNumbers = List<Int>

fun part1(input: String): Int {
    val (rules, listOfNumbers) = parse(input)
    return listOfNumbers
        .filter { numbers -> numbers == sort(numbers, rules) }
        .sumOf { numbers -> numbers[numbers.size / 2] }
}

fun part2(input: String): Int {
    val (rules, listOfNumbers) = parse(input)
    return listOfNumbers
        .filterNot { numbers -> numbers == sort(numbers, rules) }
        .map { numbers -> sort(numbers, rules) }
        .sumOf { numbers -> numbers[numbers.size / 2] }
}

private fun sort(numbers: PageNumbers, rules: List<Rule>): PageNumbers {
    return numbers.sortedWith { a, b -> if (rules.contains(a to b)) -1 else 1 }
}

private fun parse(input: String): Pair<List<Rule>, List<PageNumbers>> {
    val (rulesSection, numbersSection) = input.split("\n\n")
    val rules = rulesSection.lines()
        .mapNotNull { line ->
            val parts = line.split('|').map { it.toInt() }
            if (parts.size >= 2) parts[0] to parts[1] else null
        }
    val numbers = numbersSection.lines()
        .map { line -> line.split(',').map { it.toInt() } }
    return rules to numbers
}
permalink
report
parent
reply
1 point

I wasn’t being sarcastic, but yeah even better

permalink
report
parent
reply
5 points

C#

using QuickGraph;
using QuickGraph.Algorithms.TopologicalSort;
public class Day05 : Solver
{
  private List<int[]> updates;
  private List<int[]> updates_ordered;

  public void Presolve(string input) {
    var blocks = input.Trim().Split("\n\n");
    List<(int, int)> rules = new();
    foreach (var line in blocks[0].Split("\n")) {
      var pair = line.Split('|');
      rules.Add((int.Parse(pair[0]), int.Parse(pair[1])));
    }
    updates = new();
    updates_ordered = new();
    foreach (var line in input.Trim().Split("\n\n")[1].Split("\n")) {
      var update = line.Split(',').Select(int.Parse).ToArray();
      updates.Add(update);

      var graph = new AdjacencyGraph<int, Edge<int>>();
      graph.AddVertexRange(update);
      graph.AddEdgeRange(rules
        .Where(rule => update.Contains(rule.Item1) && update.Contains(rule.Item2))
        .Select(rule => new Edge<int>(rule.Item1, rule.Item2)));
      List<int> ordered_update = [];
      new TopologicalSortAlgorithm<int, Edge<int>>(graph).Compute(ordered_update);
      updates_ordered.Add(ordered_update.ToArray());
    }
  }

  public string SolveFirst() => updates.Zip(updates_ordered)
    .Where(unordered_ordered => unordered_ordered.First.SequenceEqual(unordered_ordered.Second))
    .Select(unordered_ordered => unordered_ordered.First)
    .Select(update => update[update.Length / 2])
    .Sum().ToString();

  public string SolveSecond() => updates.Zip(updates_ordered)
    .Where(unordered_ordered => !unordered_ordered.First.SequenceEqual(unordered_ordered.Second))
    .Select(unordered_ordered => unordered_ordered.Second)
    .Select(update => update[update.Length / 2])
    .Sum().ToString();
}
permalink
report
reply
2 points

Oh! Sort first and then check for equality. Clever!

permalink
report
parent
reply
2 points

You’ll need to sort them anyway :)

(my first version of the first part only checked the order, without sorting).

permalink
report
parent
reply
5 points

Factor

: get-input ( -- rules updates )
  "vocab:aoc-2024/05/input.txt" utf8 file-lines
  { "" } split1
  "|" "," [ '[ [ _ split ] map ] ] bi@ bi* ;

: relevant-rules ( rules update -- rules' )
  '[ [ _ in? ] all? ] filter ;

: compliant? ( rules update -- ? )
  [ relevant-rules ] keep-under
  [ [ index* ] with map first2 < ] with all? ;

: middle-number ( update -- n )
  dup length 2 /i nth-of string>number ;

: part1 ( -- n )
  get-input
  [ compliant? ] with
  [ middle-number ] filter-map sum ;

: compare-pages ( rules page1 page2 -- <=> )
  [ 2array relevant-rules ] keep-under
  [ drop +eq+ ] [ first index zero? +gt+ +lt+ ? ] if-empty ;

: correct-update ( rules update -- update' )
  [ swapd compare-pages ] with sort-with ;

: part2 ( -- n )
  get-input dupd
  [ compliant? ] with reject
  [ correct-update middle-number ] with map-sum ;

on GitHub

permalink
report
reply
4 points

Uiua

Well it’s still today here, and this is how I spent my evening. It’s not pretty or maybe even good, but it works on the test data…

spoiler

Uses Kahn’s algorithm with simplifying assumptions based on the helpful nature of the data.

Try it here

Data  ()⊸≠@\n "47|53\n97|13\n97|61\n97|47\n75|29\n61|13\n75|53\n29|13\n97|29\n53|29\n61|53\n97|53\n61|29\n47|13\n75|47\n97|75\n47|61\n75|61\n47|29\n75|13\n53|13\n\n75,47,61,53,29\n97,61,53,29,13\n75,29,13\n75,97,47,61,53\n61,13,29\n97,13,75,29,47"
Rs    ≡◇(⊜⋕⊸≠@|)▽⊸≡◇(⧻⊚⌕@|)Data
Ps    ≡⍚(⊜⋕⊸≠@,)▽⊸≡◇(¬⧻⊚⌕@|)Data

NoPred   ⊢▽:((=0/+⌕)⊙¤)◴♭⟜≡⊣                # Find entry without predecessors.
GetLead  (:((¬/+=))⊙¤)NoPred             # Remove that leading entry.
Rules    ⇌⊂⊃(⇌⊢°□⊢|≡°□↘1)[□⍢(GetLead|≠1)] Rs # Repeatedly find rule without predecessors (Kaaaaaahn!).

Sorted    ⊏⍏⊗,Rules
IsSorted  /×>0≡/-◫2⊗°□: Rules
MidVal    :(⌊÷ 2)

⇌⊕□⊸≡IsSorted Ps        # Group by whether the pages are in sort order.
≡◇(/+≡◇(MidVal Sorted)) # Find midpoints and sum.

permalink
report
reply
3 points

Does this language ever look pretty? Great for signaling UFOs though :D

permalink
report
parent
reply
2 points

Ah, but the terseness of the code allows the beauty of the underlying algorithm to shine through :-)

permalink
report
parent
reply
2 points

Those unicode code points won’t use themselves.

permalink
report
parent
reply
2 points
*

Oh my. I just watched yernab’s video, and this becomes so much easier:

# Order is totally specified, so sort by number of predecessors,
# check to see which were already sorted, then group and sum each group.
Data  (□⊜□⊸≠@\n)(¬⦷"\n\n")"47|53\n97|13\n97|61\n97|47\n75|29\n61|13\n75|53\n29|13\n97|29\n53|29\n61|53\n97|53\n61|29\n47|13\n75|47\n97|75\n47|61\n75|61\n47|29\n75|13\n53|13\n\n75,47,61,53,29\n97,61,53,29,13\n75,29,13\n75,97,47,61,53\n61,13,29\n97,13,75,29,47"
Rs    ≡◇(⊜⋕⊸≠@|)°□⊢Data
Ps    ≡⍚(⊜⋕⊸≠@,)°□⊣Data
(/+≡◇(⊡⌊÷2⧻.))¬≡≍⟜:≡⍚(⊏⍏/+⊞(Rs)..).Ps
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

  • 479

    Monthly active users

  • 109

    Posts

  • 1.1K

    Comments