this post was submitted on 05 Dec 2024
26 points (100.0% liked)

Advent Of Code

982 readers
59 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 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

(page 2) 7 comments
sorted by: hot top controversial new old
[โ€“] [email protected] 1 points 2 weeks ago

Rust

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);
}
[โ€“] [email protected] 1 points 2 weeks ago

TypeScript

Solution

import { AdventOfCodeSolutionFunction } from "./solutions";

type RulesType = Map<number, Array<number>>;

const ReduceMiddleNumbers = (p: number, v: Array<number>) => p + v[(v.length - 1) / 2];

const CheckPages = (pages: Array<number>, rules: RulesType): [true] | [false, number, number] => {
    for (let index = 0; index < pages.length; index++) {
        const page = pages[index]; // [97,61,53,29,13] => 97
        const elementRules = rules.get(page);

        // there are no rules for this number
        if (elementRules === undefined)
            continue;

        for (let ruleIndex = 0; ruleIndex < elementRules.length; ruleIndex++) {
            const rule = elementRules[ruleIndex];
            const rulePos = pages.indexOf(rule);

            // the number specified in the rule doesn't exist in our page
            if (rulePos == -1)
                continue;

            // the number came before our current index, meaning it's bad.
            if (index > rulePos) 
                return [false, index, rulePos];
        }
    }

    return [true];
}


const Reposition = (pages: Array<number>, rules: RulesType) => {
    const newPages = [...pages];
    let res = CheckPages(newPages, rules);
    let i = 0; 
    // this will be public facing api and it's possible to create inf loops so, 10k limit
    while(!res[0] && i++ < 10000) {
        // yes I know the trick, but tricks < semantics
        const moveThisRight = newPages[res[1]];
        const moveThisLeft = newPages[res[2]];
        newPages[res[1]] = moveThisLeft;
        newPages[res[2]] = moveThisRight;

        res = CheckPages(newPages, rules);
    }

    return [...newPages];
}

export const solution_5: AdventOfCodeSolutionFunction = (input) => {
    const [rules_input, content_input] = input.split("\n\n").map(v => v.trim());

    const rules: RulesType = new Map();

    rules_input.split("\n").map(v => v.split("|").map(v => Number(v))).forEach((rule) => {
        const [k, v] = rule;
        if (rules.has(k))
            rules.get(k)!.push(v);
        else
            rules.set(k, [v]);
    });

    const correctArray: Array<Array<number>> = [];
    const incorrectArray: Array<Array<number>> = [];

    content_input.split("\n").map(v => v.split(",").map(v => Number(v))).forEach(pages => {
        if(CheckPages(pages, rules)[0])
            correctArray.push(pages);
        else
            incorrectArray.push(pages);
    });

    const part_1 = correctArray.reduce<number>(ReduceMiddleNumbers, 0);
    const part_2 = incorrectArray.map((v) => Reposition([...v], rules)).reduce<number>(ReduceMiddleNumbers, 0);

    return {
        part_1,
        part_2,
    }
}

[โ€“] [email protected] 1 points 2 weeks ago

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

[โ€“] [email protected] 1 points 2 weeks ago* (last edited 2 weeks ago)

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
load more comments
view more: โ€น prev next โ€บ