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
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465
I’ve got a “smart” solution and a really dumb one. I’ll start with the smart one (incomplete but you can infer). I did four different ways to try to get it faster, less memory, etc.
// this is from a nuget package. My Mathy roommate told me this was a topological sort. // It's also my preferred, since it'd perform better on larger data sets. return lines .AsParallel() .Where(line => !IsInOrder(GetSoonestOccurrences(line), aggregateRules)) .Sum(line => line.StableOrderTopologicallyBy( getDependencies: page => aggregateRules.TryGetValue(page, out var mustPreceed) ? mustPreceed.Intersect(line) : Enumerable.Empty<Page>()) .Middle() );
The dumb solution. These comparisons aren’t fully transitive. I can’t believe it works.
public static SortedSet<Page> Sort3(Page[] line, Dictionary<Page, System.Collections.Generic.HashSet<Page>> rules) { // how the hell is this working? var sorted = new SortedSet<Page>(new Sort3Comparer(rules)); foreach (var page in line) sorted.Add(page); return sorted; } public static Page[] OrderBy(Page[] line, Dictionary<Page, System.Collections.Generic.HashSet<Page>> rules) { return line.OrderBy(identity, new Sort3Comparer(rules)).ToArray(); } sealed class Sort3Comparer : IComparer<Page> { private readonly Dictionary<Page, System.Collections.Generic.HashSet<Page>> _rules; public Sort3Comparer(Dictionary<Page, System.Collections.Generic.HashSet<Page>> rules) => _rules = rules; public int Compare(Page x, Page y) { if (_rules.TryGetValue(x, out var xrules)) { if (xrules.Contains(y)) return -1; } if (_rules.TryGetValue(y, out var yrules)) { if (yrules.Contains(x)) return 1; } return 0; } }
Method Mean Error StdDev Gen0 Gen1 Allocated Part2_UsingList (literally just Insert) 660.3 us 12.87 us 23.20 us 187.5000 35.1563 1144.86 KB Part2_TrackLinkedList (wrong now) 1,559.7 us 6.91 us 6.46 us 128.9063 21.4844 795.03 KB Part2_TopologicalSort 732.3 us 13.97 us 16.09 us 285.1563 61.5234 1718.36 KB Part2_SortedSet 309.1 us 4.13 us 3.45 us 54.1992 10.2539 328.97 KB Part2_OrderBy 304.5 us 6.09 us 9.11 us 48.8281 7.8125 301.29 KB 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.
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.
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
Does this language ever look pretty? Great for signaling UFOs though :D
Ah, but the terseness of the code allows the beauty of the underlying algorithm to shine through :-)
Those unicode code points won’t use themselves.
Uiua
This is the first one that caused me some headache because I didn’t read the instructions carefully enough.
I kept trying to create a sorted list for when all available pages were used, which got me stuck in an endless loop.Another fun part was figuring out to use
memberof (∈)
instead offind (⌕)
in the last line ofFindNext
. So much time spent on debugging other areas of the codeRun with example input here
FindNext ← ⊙( ⊡1⍉, ⊃▽(▽¬)⊸∈ ⊙⊙(⊡0⍉.) :⊙(⟜(▽¬∈)) ) # find the order of pages for a given set of rules FindOrder ← ( ◴♭. [] ⍢(⊂FindNext|⋅(>1⧻)) ⊙◌⊂ ) PartOne ← ( &rs ∞ &fo "input-5.txt" ∩°□°⊟⊜□¬⌕"\n\n". ⊙(⊜(□⊜⋕≠@,.)≠@\n.↘1) ⊜(⊜⋕≠@|.)≠@\n. ⊙. ¤ ⊞(◡(°□:) ⟜:⊙(°⊟⍉) =2+∩∈ ▽ FindOrder ⊸≍°□: ⊙◌ ) ≡◇(⊡⌊÷2⧻.)▽♭ /+ ) PartTwo ← ( &rs ∞ &fo "input-5.txt" ∩°□°⊟⊜□¬⌕"\n\n". ⊙(⊜(□⊜⋕≠@,.)≠@\n.↘1) ⊜(⊜⋕≠@|.)≠@\n. ⊙. ⍜¤⊞( ◡(°□:) ⟜:⊙(°⊟⍉) =2+∩∈ ▽ FindOrder ⊸≍°□: ⊟∩□ ) ⊙◌ ⊃(⊡0)(⊡1)⍉ ≡◇(⊡⌊÷2⧻.)▽¬≡°□ /+ ) &p "Day 5:" &pf "Part 1: " &p PartOne &pf "Part 2: " &p PartTwo
Nim
import ../aoc, strutils, sequtils, tables type Rules = ref Table[int, seq[int]] #check if an update sequence is valid proc valid(update:seq[int], rules:Rules):bool = for pi, p in update: for r in rules.getOrDefault(p): let ri = update.find(r) if ri != -1 and ri < pi: return false return true proc backtrack(p:int, index:int, update:seq[int], rules: Rules, sorted: var seq[int]):bool = if index == 0: sorted[index] = p return true for r in rules.getOrDefault(p): if r in update and r.backtrack(index-1, update, rules, sorted): sorted[index] = p return true return false #fix an invalid sequence proc fix(update:seq[int], rules: Rules):seq[int] = echo "fixing", update var sorted = newSeqWith(update.len, 0); for p in update: if p.backtrack(update.len-1, update, rules, sorted): return sorted return @[] proc solve*(input:string): array[2,int] = let parts = input.split("\r\n\r\n"); let rulePairs = parts[0].splitLines.mapIt(it.strip.split('|').map(parseInt)) let updates = parts[1].splitLines.mapIt(it.split(',').map(parseInt)) # fill rules table var rules = new Rules for rp in rulePairs: if rules.hasKey(rp[0]): rules[rp[0]].add rp[1]; else: rules[rp[0]] = @[rp[1]] # fill reverse rules table var backRules = new Rules for rp in rulePairs: if backRules.hasKey(rp[1]): backRules[rp[1]].add rp[0]; else: backRules[rp[1]] = @[rp[0]] for u in updates: if u.valid(rules): result[0] += u[u.len div 2] else: let uf = u.fix(backRules) result[1] += uf[uf.len div 2]
I thought of doing a sort at first, but dismissed it for some reason, so I came up with this slow and bulky recursive backtracking thing which traverses the rules as a graph until it reaches a depth equal to the given sequence. Not my finest work, but it does solve the puzzle :)
Lisp
Part 1 and 2
(defun p1-process-rules (line) (mapcar #'parse-integer (uiop:split-string line :separator "|"))) (defun p1-process-pages (line) (mapcar #'parse-integer (uiop:split-string line :separator ","))) (defun middle (pages) (nth (floor (length pages) 2) pages)) (defun check-rule-p (rule pages) (let ((p1 (position (car rule) pages)) (p2 (position (cadr rule) pages))) (or (not p1) (not p2) (< p1 p2)))) (defun ordered-p (pages rules) (loop for r in rules unless (check-rule-p r pages) return nil finally (return t))) (defun run-p1 (rules-file pages-file) (let ((rules (read-file rules-file #'p1-process-rules)) (pages (read-file pages-file #'p1-process-pages))) (loop for p in pages when (ordered-p p rules) sum (middle p) ))) (defun fix-pages (rules pages) (sort pages (lambda (p1 p2) (ordered-p (list p1 p2) rules)) )) (defun run-p2 (rules-file pages-file) (let ((rules (read-file rules-file #'p1-process-rules)) (pages (read-file pages-file #'p1-process-pages))) (loop for p in pages unless (ordered-p p rules) sum (middle (fix-pages rules p)) )))
Zig
const std = @import("std"); const List = std.ArrayList; const Map = std.AutoHashMap; const tokenizeScalar = std.mem.tokenizeScalar; const splitScalar = std.mem.splitScalar; const parseInt = std.fmt.parseInt; const print = std.debug.print; const contains = std.mem.containsAtLeast; const eql = std.mem.eql; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const alloc = gpa.allocator(); const Answer = struct { middle_sum: i32, reordered_sum: i32, }; pub fn solve(input: []const u8) !Answer { var rows = splitScalar(u8, input, '\n'); // key is a page number and value is a // list of pages to be printed before it var rules = Map(i32, List(i32)).init(alloc); var pages = List([]i32).init(alloc); defer { var iter = rules.iterator(); while (iter.next()) |rule| { rule.value_ptr.deinit(); } rules.deinit(); pages.deinit(); } var parse_rules = true; while (rows.next()) |row| { if (eql(u8, row, "")) { parse_rules = false; continue; } if (parse_rules) { var rule_pair = tokenizeScalar(u8, row, '|'); const rule = try rules.getOrPut(try parseInt(i32, rule_pair.next().?, 10)); if (!rule.found_existing) { rule.value_ptr.* = List(i32).init(alloc); } try rule.value_ptr.*.append(try parseInt(i32, rule_pair.next().?, 10)); } else { var page = List(i32).init(alloc); var page_list = tokenizeScalar(u8, row, ','); while (page_list.next()) |list| { try page.append(try parseInt(i32, list, 10)); } try pages.append(try page.toOwnedSlice()); } } var middle_sum: i32 = 0; var reordered_sum: i32 = 0; var wrong_order = false; for (pages.items) |page| { var index: usize = page.len - 1; while (index > 0) : (index -= 1) { var page_rule = rules.get(page[index]) orelse continue; // check the rest of the pages var remaining: usize = 0; while (remaining < page[0..index].len) { if (contains(i32, page_rule.items, 1, &[_]i32{page[remaining]})) { // re-order the wrong page const element = page[remaining]; page[remaining] = page[index]; page[index] = element; wrong_order = true; if (rules.get(element)) |next_rule| { page_rule = next_rule; } continue; } remaining += 1; } } if (wrong_order) { reordered_sum += page[(page.len - 1) / 2]; wrong_order = false; } else { // middle page number middle_sum += page[(page.len - 1) / 2]; } } return Answer{ .middle_sum = middle_sum, .reordered_sum = reordered_sum }; } pub fn main() !void { const answer = try solve(@embedFile("input.txt")); print("Part 1: {d}\n", .{answer.middle_sum}); print("Part 2: {d}\n", .{answer.reordered_sum}); } test "test input" { const answer = try solve(@embedFile("test.txt")); try std.testing.expectEqual(143, answer.middle_sum); try std.testing.expectEqual(123, answer.reordered_sum); }
Elixir
defmodule AdventOfCode.Solution.Year2024.Day05 do use AdventOfCode.Solution.SharedParse @impl true def parse(input) do [rules, pages_list] = String.split(input, "\n\n", limit: 2) |> Enum.map(&String.split(&1, "\n", trim: true)) {for(rule <- rules, do: String.split(rule, "|") |> Enum.map(&String.to_integer/1)) |> MapSet.new(), for(pages <- pages_list, do: String.split(pages, ",") |> Enum.map(&String.to_integer/1))} end def part1({rules, pages_list}), do: solve(rules, pages_list, false) def part2({rules, pages_list}), do: solve(rules, pages_list, true) def solve(rules, pages_list, negate) do for pages <- pages_list, reduce: 0 do total -> ordered = Enum.sort(pages, &([&1, &2] in rules)) if negate != (ordered == pages), do: total + Enum.at(ordered, div(length(ordered), 2)), else: total end end end
Julia
No really proud of todays solution. Probably because I started too late today.
I used a dictionary with the numbers that should be in front of any given number. Then I checked if they appear after that number. Part1 check. For part 2 I just hoped for the best that ordering it would work by switching each two problematic entries and it worked.
::: spoiler
function readInput(inputFile::String) f = open(inputFile,"r"); lines::Vector{String} = readlines(f); close(f) updates::Vector{Vector{Int}} = [] pageOrderingRules = Dict{Int,Vector{Int}}() readRules::Bool = true #switch off after rules are read, then read updates for (i,line) in enumerate(lines) line=="" ? (readRules=false;continue) : nothing if readRules values::Vector{Int} = map(x->parse(Int,x),split(line,"|")) !haskey(pageOrderingRules,values[2]) ? pageOrderingRules[values[2]]=Vector{Int}() : nothing push!(pageOrderingRules[values[2]],values[1]) else #read updates push!(updates,map(x->parse(Int,x),split(line,","))) end end return updates, pageOrderingRules end function checkUpdateInOrder(update::Vector{Int},pageOrderingRules::Dict{Int,Vector{Int}})::Bool inCorrectOrder::Bool = true for i=1 : length(update)-1 for j=i+1 : length(update) !haskey(pageOrderingRules,update[i]) ? continue : nothing update[j] in pageOrderingRules[update[i]] ? inCorrectOrder=false : nothing end !inCorrectOrder ? break : nothing end return inCorrectOrder end function calcMidNumSum(updates::Vector{Vector{Int}},pageOrderingRules::Dict{Int,Vector{Int}})::Int midNumSum::Int = 0 for update in updates checkUpdateInOrder(update,pageOrderingRules) ? midNumSum+=update[Int(ceil(length(update)/2))] : nothing end return midNumSum end function calcMidNumSumForCorrected(updates::Vector{Vector{Int}},pageOrderingRules::Dict{Int,Vector{Int}})::Int midNumSum::Int = 0 for update in updates inCorrectOrder::Bool = checkUpdateInOrder(update,pageOrderingRules) inCorrectOrder ? continue : nothing #skip already correct updates while !inCorrectOrder for i=1 : length(update)-1 for j=i+1 : length(update) !haskey(pageOrderingRules,update[i]) ? continue : nothing if update[j] in pageOrderingRules[update[i]] mem::Int = update[i]; update[i] = update[j]; update[j]=mem #switch entries end end end inCorrectOrder = checkUpdateInOrder(update,pageOrderingRules) end midNumSum += update[Int(ceil(length(update)/2))] end return midNumSum end updates, pageOrderingRules = readInput("day05Input") println("part 1 sum: $(calcMidNumSum(updates,pageOrderingRules))") println("part 2 sum: $(calcMidNumSumForCorrected(updates,pageOrderingRules))")
:::
Kotlin
That was an easy one, once you define a comparator function. (At least when you have a sorting function in your standard-library.) The biggest part was the parsing. lol
import kotlin.text.Regex fun main() { fun part1(input: List<String>): Int = parseInput(input).sumOf { if (it.isCorrectlyOrdered()) it[it.size / 2].pageNumber else 0 } fun part2(input: List<String>): Int = parseInput(input).sumOf { if (!it.isCorrectlyOrdered()) it.sorted()[it.size / 2].pageNumber else 0 } val testInput = readInput("Day05_test") check(part1(testInput) == 143) check(part2(testInput) == 123) val input = readInput("Day05") part1(input).println() part2(input).println() } fun parseInput(input: List<String>): List<List<Page>> { val (orderRulesStrings, pageSequencesStrings) = input.filter { it.isNotEmpty() }.partition { Regex("""\d+\|\d+""").matches(it) } val orderRules = orderRulesStrings.map { with(it.split('|')) { this[0].toInt() to this[1].toInt() } } val orderRulesX = orderRules.map { it.first }.toSet() val pages = orderRulesX.map { pageNumber -> val orderClasses = orderRules.filter { it.first == pageNumber }.map { it.second } Page(pageNumber, orderClasses) }.associateBy { it.pageNumber } val pageSequences = pageSequencesStrings.map { sequenceString -> sequenceString.split(',').map { pages[it.toInt()] ?: Page(it.toInt(), emptyList()) } } return pageSequences } /* * An order class is an equivalence class for every page with the same page to be printed before. */ data class Page(val pageNumber: Int, val orderClasses: List<Int>): Comparable<Page> { override fun compareTo(other: Page): Int = if (other.pageNumber in orderClasses) -1 else if (pageNumber in other.orderClasses) 1 else 0 } fun List<Page>.isCorrectlyOrdered(): Boolean = this == this.sorted()
Nim
Solution: sort numbers using custom rules and compare if sorted == original. Part 2 is trivial.
Runtime for both parts: 1.05 msproc 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]
Nice, compact and easy to follow. The implicit
result
object reminds me of Visual Basic.
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 }
I like how clean this is
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 }
I wasn’t being sarcastic, but yeah even better
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 ;
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(); }
Oh! Sort first and then check for equality. Clever!
You’ll need to sort them anyway :)
(my first version of the first part only checked the order, without sorting).
Haskell
Part two was actually much easier than I thought it was!
import Control.Arrow import Data.Bool import Data.List import Data.List.Split import Data.Maybe readInput :: String -> ([(Int, Int)], [[Int]]) readInput = (readRules *** readUpdates . tail) . break null . lines where readRules = map $ (read *** read . tail) . break (== '|') readUpdates = map $ map read . splitOn "," mid = (!!) <*> ((`div` 2) . length) isSortedBy rules = (`all` rules) . match where match ps (x, y) = fromMaybe True $ (<) <$> elemIndex x ps <*> elemIndex y ps pageOrder rules = curry $ bool GT LT . (`elem` rules) main = do (rules, updates) <- readInput <$> readFile "input05" let (part1, part2) = partition (isSortedBy rules) updates mapM_ (print . sum . map mid) [part1, sortBy (pageOrder rules) <$> part2]
Dart
A bit easier than I first thought it was going to be.
I had a look at the Uiua discussion, and this one looks to be beyond my pay grade, so this will be it for today.
import 'package:collection/collection.dart'; import 'package:more/more.dart'; (int, int) solve(List<String> lines) { var parts = lines.splitAfter((e) => e == ''); var pred = SetMultimap.fromEntries(parts.first.skipLast(1).map((e) { var ps = e.split('|').map(int.parse); return MapEntry(ps.last, ps.first); })); ordering(a, b) => pred[a].contains(b) ? 1 : 0; var pageSets = parts.last.map((e) => e.split(',').map(int.parse).toList()); var partn = pageSets.partition((ps) => ps.isSorted(ordering)); return ( partn.truthy.map((e) => e[e.length ~/ 2]).sum, partn.falsey.map((e) => (e..sort(ordering))[e.length ~/ 2]).sum ); } part1(List<String> lines) => solve(lines).$1; part2(List<String> lines) => solve(lines).$2;