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