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
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
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]
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
Real thinker. Messed around with a couple solutions before this one. The gist is to take all the pairwise comparisons given and record them for easy access in a ranking matrix.
For the sample input, this grid would look like this (I left out all the non-present integers, but it would be a 98 x 98 grid where all the empty spaces are filled with Ordering::Equal):
I discovered this can't be used for a total order on the actual puzzle input because there were cycles in the pairs given (see how rust changed sort implementations as of 1.81). I used usize for convenience (I did it with u8 for all the pair values originally, but kept having to cast over and over as usize). Didn't notice a performance difference, but I'm sure uses a bit more memory.
Also I Liked the simple_grid crate a little better than the grid one. Will have to refactor that out at some point.
*Edit: I did try switching to just using std::collections::HashMap, but it was 0.1 ms slower on average than using the simple_grid::Grid... Vec[idx] access is faster maybe?
While part 1 was pretty quick, part 2 took me a while to figure something out. I figured that the relation would probably be a total ordering, and obtained the actual order using topological sorting. But it turns out the relation has cycles, so the topological sort must be limited to the elements that actually occur in the lists.
Solution
use std::collections::{HashSet, HashMap, VecDeque};
fn parse_lists(input: &str) -> Vec<Vec<u32>> {
input.lines()
.map(|l| l.split(',').map(|e| e.parse().unwrap()).collect())
.collect()
}
fn parse_relation(input: String) -> (HashSet<(u32, u32)>, Vec<Vec<u32>>) {
let (ordering, lists) = input.split_once("\n\n").unwrap();
let relation = ordering.lines()
.map(|l| {
let (a, b) = l.split_once('|').unwrap();
(a.parse().unwrap(), b.parse().unwrap())
})
.collect();
(relation, parse_lists(lists))
}
fn parse_graph(input: String) -> (Vec<Vec<u32>>, Vec<Vec<u32>>) {
let (ordering, lists) = input.split_once("\n\n").unwrap();
let mut graph = Vec::new();
for l in ordering.lines() {
let (a, b) = l.split_once('|').unwrap();
let v: u32 = a.parse().unwrap();
let w: u32 = b.parse().unwrap();
let new_len = v.max(w) as usize + 1;
if new_len > graph.len() {
graph.resize(new_len, Vec::new())
}
graph[v as usize].push(w);
}
(graph, parse_lists(lists))
}
fn part1(input: String) {
let (relation, lists) = parse_relation(input);
let mut sum = 0;
for l in lists {
let mut valid = true;
for i in 0..l.len() {
for j in 0..i {
if relation.contains(&(l[i], l[j])) {
valid = false;
break
}
}
if !valid { break }
}
if valid {
sum += l[l.len() / 2];
}
}
println!("{sum}");
}
// Topological order of graph, but limited to nodes in the set `subgraph`.
// Otherwise the graph is not acyclic.
fn topological_sort(graph: &[Vec<u32>], subgraph: &HashSet<u32>) -> Vec<u32> {
let mut order = VecDeque::with_capacity(subgraph.len());
let mut marked = vec![false; graph.len()];
for &v in subgraph {
if !marked[v as usize] {
dfs(graph, subgraph, v as usize, &mut marked, &mut order)
}
}
order.into()
}
fn dfs(graph: &[Vec<u32>], subgraph: &HashSet<u32>, v: usize, marked: &mut [bool], order: &mut VecDeque<u32>) {
marked[v] = true;
for &w in graph[v].iter().filter(|v| subgraph.contains(v)) {
if !marked[w as usize] {
dfs(graph, subgraph, w as usize, marked, order);
}
}
order.push_front(v as u32);
}
fn rank(order: &[u32]) -> HashMap<u32, u32> {
order.iter().enumerate().map(|(i, x)| (*x, i as u32)).collect()
}
// Part 1 with topological sorting, which is slower
fn _part1(input: String) {
let (graph, lists) = parse_graph(input);
let mut sum = 0;
for l in lists {
let subgraph = HashSet::from_iter(l.iter().copied());
let rank = rank(&topological_sort(&graph, &subgraph));
if l.is_sorted_by_key(|x| rank[x]) {
sum += l[l.len() / 2];
}
}
println!("{sum}");
}
fn part2(input: String) {
let (graph, lists) = parse_graph(input);
let mut sum = 0;
for mut l in lists {
let subgraph = HashSet::from_iter(l.iter().copied());
let rank = rank(&topological_sort(&graph, &subgraph));
if !l.is_sorted_by_key(|x| rank[x]) {
l.sort_unstable_by_key(|x| rank[x]);
sum += l[l.len() / 2];
}
}
println!("{sum}");
}
util::aoc_main!();
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 :)
Well, this one ended up with a surprisingly easy part 2 with how I wrote it.
Not the most computationally optimal code, but since they're still cheap enough to run in milliseconds I'm not overly bothered.
C#
class OrderComparer : IComparer<int>
{
Dictionary<int, List<int>> ordering;
public OrderComparer(Dictionary<int, List<int>> ordering) {
this.ordering = ordering;
}
public int Compare(int x, int y)
{
if (ordering.ContainsKey(x) && ordering[x].Contains(y))
return -1;
return 1;
}
}
Dictionary<int, List<int>> ordering = new Dictionary<int, List<int>>();
int[][] updates = new int[0][];
public void Input(IEnumerable<string> lines)
{
foreach (var pair in lines.TakeWhile(l => l.Contains('|')).Select(l => l.Split('|').Select(w => int.Parse(w))))
{
if (!ordering.ContainsKey(pair.First()))
ordering[pair.First()] = new List<int>();
ordering[pair.First()].Add(pair.Last());
}
updates = lines.SkipWhile(s => s.Contains('|') || string.IsNullOrWhiteSpace(s)).Select(l => l.Split(',').Select(w => int.Parse(w)).ToArray()).ToArray();
}
public void Part1()
{
int correct = 0;
var comparer = new OrderComparer(ordering);
foreach (var update in updates)
{
var ordered = update.Order(comparer);
if (update.SequenceEqual(ordered))
correct += ordered.Skip(ordered.Count() / 2).First();
}
Console.WriteLine($"Sum: {correct}");
}
public void Part2()
{
int incorrect = 0;
var comparer = new OrderComparer(ordering);
foreach (var update in updates)
{
var ordered = update.Order(comparer);
if (!update.SequenceEqual(ordered))
incorrect += ordered.Skip(ordered.Count() / 2).First();
}
Console.WriteLine($"Sum: {incorrect}");
}
from math import floor
from pathlib import Path
from functools import cmp_to_key
cwd = Path(__file__).parent
def parse_protocol(path):
with path.open("r") as fp:
data = fp.read().splitlines()
rules = data[:data.index('')]
page_to_rule = {r.split('|')[0]:[] for r in rules}
[page_to_rule[r.split('|')[0]].append(r.split('|')[1]) for r in rules]
updates = list(map(lambda x: x.split(','), data[data.index('')+1:]))
return page_to_rule, updates
def sort_pages(pages, page_to_rule):
compare_pages = lambda page1, page2:\
0 if page1 not in page_to_rule or page2 not in page_to_rule[page1] else -1
return sorted(pages, key = cmp_to_key(compare_pages))
def solve_problem(file_name, fix):
page_to_rule, updates = parse_protocol(Path(cwd, file_name))
to_print = [temp_p[int(floor(len(pages)/2))] for pages in updates
if (not fix and (temp_p:=pages) == sort_pages(pages, page_to_rule))
or (fix and (temp_p:=sort_pages(pages, page_to_rule)) != pages)]
return sum(map(int,to_print))
I got the question so wrong - I thought a|b and b|c would imply a|c so I went and used dynamic programming to propagate indirect relations through a table.
It worked beautifully but not for the input, which doesn't describe an absolute global ordering at all. It may well give a|c and b|c AND c|a. Nothing can be deduced then, and nothing needs to, because all required relations are directly specified.
The table works great though, the sort comparator is a simple 2D array index, so O(1).
Code
#include "common.h"
#define TSZ 100
#define ASZ 32
/* tab[a][b] is -1 if a<b and 1 if a>b */
static int8_t tab[TSZ][TSZ];
static int
cmp(const void *a, const void *b)
{
return tab[*(const int *)a][*(const int *)b];
}
int
main(int argc, char **argv)
{
char buf[128], *rest, *tok;
int p1=0,p2=0, arr[ASZ],srt[ASZ], n,i, a,b;
if (argc > 1)
DISCARD(freopen(argv[1], "r", stdin));
while (fgets(buf, sizeof(buf), stdin)) {
if (sscanf(buf, "%d|%d", &a, &b) != 2)
break;
assert(a>=0); assert(a<TSZ);
assert(b>=0); assert(b<TSZ);
tab[a][b] = -(tab[b][a] = 1);
}
while ((rest = fgets(buf, sizeof(buf), stdin))) {
for (n=0; (tok = strsep(&rest, ",")); n++) {
assert(n < (int)LEN(arr));
sscanf(tok, "%d", &arr[n]);
}
memcpy(srt, arr, n*sizeof(*srt));
qsort(srt, n, sizeof(*srt), cmp);
*(memcmp(srt, arr, n*sizeof(*srt)) ? &p1 : &p2) += srt[n/2];
}
printf("05: %d %d\n", p1, p2);
return 0;
}
Same, I initially also thought a|b and a|c implies a|c. However when I drew the graph of the example on paper, I suspected that all relations will be given, and coded it with that assumption, that turned out to be correct
from functools import cmp_to_key
from pathlib import Path
def parse_input(input: str) -> tuple[dict[int, list[int]], list[list[int]]]:
rules, updates = tuple(input.strip().split("\n\n")[:2])
order = {}
for entry in rules.splitlines():
values = entry.split("|")
order.setdefault(int(values[0]), []).append(int(values[1]))
updates = [[int(v) for v in u.split(",")] for u in updates.splitlines()]
return (order, updates)
def is_ordered(update: list[int], order: dict[int, list[int]]) -> bool:
return update == sorted(
update, key=cmp_to_key(lambda a, b: 1 if a in order.setdefault(b, []) else -1)
)
def part_one(input: str) -> int:
order, updates = parse_input(input)
return sum([u[len(u) // 2] for u in (u for u in updates if is_ordered(u, order))])
def part_two(input: str) -> int:
order, updates = parse_input(input)
return sum(
[
sorted(u, key=cmp_to_key(lambda a, b: 1 if a in order[b] else -1))[
len(u) // 2
]
for u in (u for u in updates if not is_ordered(u, order))
]
)
if __name__ == "__main__":
input = Path("input").read_text("utf-8")
print(part_one(input))
print(part_two(input))
I was very much unhappy because my previous implementation took 1 second to execute and trashed through 2GB RAM in the process of doing so, I sat down again with some inspiration about the sorting approach.
I am very much happy now, the profiler tells me that most of time is spend in the parsing functions now.
I am also grateful for everyone else doing haskell, this way I learned about Arrays, Bifunctors and Arrows which (I think) improved my code a lot.
Haskell
import Control.Arrow hiding (first, second)
import Data.Map (Map)
import Data.Set (Set)
import Data.Bifunctor
import qualified Data.Maybe as Maybe
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Ord as Ord
parseRule :: String -> (Int, Int)
parseRule s = (read . take 2 &&& read . drop 3) s
replace t r c = if t == c then r else c
parse :: String -> (Map Int (Set Int), [[Int]])
parse s = (map parseRule >>> buildRuleMap $ rules, map (map read . words) updates)
where
rules = takeWhile (/= "") . lines $ s
updates = init . map (map (replace ',' ' ')) . drop 1 . dropWhile (/= "") . lines $ s
middleElement :: [a] -> a
middleElement us = (us !!) $ (length us `div` 2)
ruleGroup :: Eq a => (a, b) -> (a, b') -> Bool
ruleGroup = curry (uncurry (==) <<< fst *** fst)
buildRuleMap :: [(Int, Int)] -> Map Int (Set Int)
buildRuleMap rs = List.sortOn fst
>>> List.groupBy ruleGroup
>>> map ((fst . head) &&& map snd)
>>> map (second Set.fromList)
>>> Map.fromList
$ rs
elementSort :: Map Int (Set Int) -> Int -> Int -> Ordering
elementSort rs a b
| Maybe.maybe False (Set.member b) (rs Map.!? a) = LT
| Maybe.maybe False (Set.member a) (rs Map.!? b) = GT
| otherwise = EQ
isOrdered rs u = (List.sortBy (elementSort rs) u) == u
part1 (rs, us) = filter (isOrdered rs)
>>> map middleElement
>>> sum
$ us
part2 (rs, us) = filter (isOrdered rs >>> not)
>>> map (List.sortBy (elementSort rs))
>>> map middleElement
>>> sum
$ us
main = getContents >>= print . (part1 &&& part2) . parse
I should probably have used sortBy instead of this ad-hoc selection sort.
import Control.Arrow
import Control.Monad
import Data.Char
import Data.List qualified as L
import Data.Map
import Data.Set
import Data.Set qualified as S
import Text.ParserCombinators.ReadP
parse = (,) <$> (fromListWith S.union <$> parseOrder) <*> (eol *> parseUpdate)
parseOrder = endBy (flip (,) <$> (S.singleton <$> parseInt <* char '|') <*> parseInt) eol
parseUpdate = endBy (sepBy parseInt (char ',')) eol
parseInt = read <$> munch1 isDigit
eol = char '\n'
verify :: Map Int (Set Int) -> [Int] -> Bool
verify m = and . (zipWith fn <*> scanl (flip S.insert) S.empty)
where
fn a = flip S.isSubsetOf (findWithDefault S.empty a m)
getMiddle = ap (!!) ((`div` 2) . length)
part1 m = sum . fmap getMiddle
getOrigin :: Map Int (Set Int) -> Set Int -> Int
getOrigin m l = head $ L.filter (S.disjoint l . preds) (S.toList l)
where
preds = flip (findWithDefault S.empty) m
order :: Map Int (Set Int) -> Set Int -> [Int]
order m s
| S.null s = []
| otherwise = h : order m (S.delete h s)
where
h = getOrigin m s
part2 m = sum . fmap (getMiddle . order m . S.fromList)
main = getContents >>= print . uncurry runParts . fst . last . readP_to_S parse
runParts m = L.partition (verify m) >>> (part1 m *** part2 m)
Used a sorted/unsorted comparison to solve the first part, the second part was just filling out the else branch.
use std::{
cmp::Ordering,
collections::HashMap,
io::{BufRead, BufReader},
};
fn main() {
let mut lines = BufReader::new(std::fs::File::open("input.txt").unwrap()).lines();
let mut rules: HashMap<u64, Vec<u64>> = HashMap::default();
for line in lines.by_ref() {
let line = line.unwrap();
if line.is_empty() {
break;
}
let lr = line
.split('|')
.map(|el| el.parse::<u64>())
.collect::<Result<Vec<u64>, _>>()
.unwrap();
let left = lr[0];
let right = lr[1];
if let Some(values) = rules.get_mut(&left) {
values.push(right);
values.sort();
} else {
rules.insert(left, vec![right]);
}
}
let mut updates: Vec<Vec<u64>> = Vec::default();
for line in lines {
let line = line.unwrap();
let update = line
.split(',')
.map(|el| el.parse::<u64>())
.collect::<Result<Vec<u64>, _>>()
.unwrap();
updates.push(update);
}
let mut middle_sum = 0;
let mut fixed_middle_sum = 0;
for update in updates {
let mut update_sorted = update.clone();
update_sorted.sort_by(|a, b| {
if let Some(rules) = rules.get(a) {
if rules.contains(b) {
Ordering::Less
} else {
Ordering::Equal
}
} else {
Ordering::Equal
}
});
if update.eq(&update_sorted) {
let middle = update[(update.len() - 1) / 2];
middle_sum += middle;
} else {
let middle = update_sorted[(update_sorted.len() - 1) / 2];
fixed_middle_sum += middle;
}
}
println!("part1: {} part2: {}", middle_sum, fixed_middle_sum);
}
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 of find (⌕) in the last line of FindNext. So much time spent on debugging other areas of the code
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()
Part 2 was an interesting one and my solution kinda feels like cheating. What I did I only changed the validation method from part 1 to return the indexes of incorrectly placed pages and then randomly swapped those around in a loop until the validation passed. I was expecting this to not work at all or take forever to run but surprisingly it only takes three to five seconds to complete.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
public class Day05 {
private static final Random random = new Random();
public static void main(final String[] args) throws IOException {
final String input = Files.readString(Path.of("2024\\05\\input.txt"), StandardCharsets.UTF_8);
final String[] inputSplit = input.split("[\r\n]{4,}");
final List<PageOrderingRule> rules = Arrays.stream(inputSplit[0].split("[\r\n]+"))
.map(row -> row.split("\\|"))
.map(row -> new PageOrderingRule(Integer.parseInt(row[0]), Integer.parseInt(row[1])))
.toList();
final List<ArrayList<Integer>> updates = Arrays.stream(inputSplit[1].split("[\r\n]+"))
.map(row -> row.split(","))
.map(row -> Arrays.stream(row).map(Integer::parseInt).collect(Collectors.toCollection(ArrayList::new)))
.toList();
System.out.println("Part 1: " + updates.stream()
.filter(update -> validate(update, rules).isEmpty())
.mapToInt(update -> update.get(update.size() / 2))
.sum()
);
System.out.println("Part 2: " + updates.stream()
.filter(update -> !validate(update, rules).isEmpty())
.map(update -> fixOrder(update, rules))
.mapToInt(update -> update.get(update.size() / 2))
.sum()
);
}
private static Set<Integer> validate(final List<Integer> update, final List<PageOrderingRule> rules) {
final Set<Integer> invalidIndexes = new HashSet<>();
for (int i = 0; i < update.size(); i++) {
final Integer integer = update.get(i);
for (final PageOrderingRule rule : rules) {
if (rule.x == integer && update.contains(rule.y) && i > update.indexOf(rule.y)) {
invalidIndexes.add(i);
}
else if (rule.y == integer && update.contains(rule.x) && i < update.indexOf(rule.x)) {
invalidIndexes.add(i);
}
}
}
return invalidIndexes;
}
private static List<Integer> fixOrder(final List<Integer> update, final List<PageOrderingRule> rules) {
List<Integer> invalidIndexesList = new ArrayList<>(validate(update, rules));
// Swap randomly until the validation passes
while (!invalidIndexesList.isEmpty()) {
Collections.swap(update, random.nextInt(invalidIndexesList.size()), random.nextInt(invalidIndexesList.size()));
invalidIndexesList = new ArrayList<>(validate(update, rules));
}
return update;
}
private static record PageOrderingRule(int x, int y) {}
}
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.
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))")
import re
import aoc
def setup():
lines = aoc.get_lines(5)
return ([list(map(int, re.findall(r'\d+', x)))
for x in lines if re.search(r'\|', x)],
[list(map(int, re.findall(r'\d+', x)))
for x in lines if re.search(r',', x)], 0)
def one():
rules, updates, acc = setup()
for update in updates:
v = 1
for i, u in enumerate(update):
r = [x[0] for x in rules if x[1] == u and x[0] in update]
if not all(n in update[:i] for n in r):
v = 0
break
if v:
acc += update[len(update) // 2]
print(acc)
def fix(update, rules):
c = 1
while c:
c = 0
for i, u in enumerate(update):
r = [x[0] for x in rules if x[1] == u and x[0] in update]
for p in r:
pi = update.index(p)
if pi > i:
update[i], update[pi] = update[pi], update[i]
c = 1
return update[len(update) // 2]
def two():
rules, updates, acc = setup()
for update in updates:
v = 1
for i, u in enumerate(update):
r = [x[0] for x in rules if x[1] == u and x[0] in update]
if not all(n in update[:i] for n in r):
v = 0
break
if not v:
acc += fix(update, rules)
print(acc)
one()
two()
Forgot to make a separate solve for part two, for part one, imagine this without the make_valid function and some slightly different structure changes around the accumulator in babbage().
Used a hash map to track what should be in order, and a few indexed loops to keep track of where I’m at and where to look forward.
This one ended up being easier than I thought it was going to be. My algorithm for correcting the incorrect orders needed to be ran multiple times, for some reason
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;
}
}
Because you're just sorting integers and in a single pass, the a == b and a > b distinction doesn't actually matter here, so the cmp can very simply be is a|b in rules, no map needed.
Edit: I realise it would be a sidegrade for your case because of how you did P1, just thought it was an interesting insight, especially for those that did P1 by checking if the input was sorted using the same custom compare.
func solution(input string) (int, int) {
// rules: ["a|b", ...]
// updates: [[1, 2, 3, 4], ...]
var rules, updates = parse(input)
sortFunc := func(a int, b int) int {
if slices.Contains(rules, strconv.Itoa(a)+"|"+strconv.Itoa(b)) {
return -1
}
return 1
}
var sumOrdered = 0
var sumUnordered = 0
for _, update := range updates {
if slices.IsSortedFunc(update, sortFunc) {
sumOrdered += update[len(update)/2]
} else {
slices.SortStableFunc(update, sortFunc)
sumUnordered += update[len(update)/2]
}
}
return sumOrdered, sumUnordered
}