Day 1: Dusty Shed

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

  • Unusable 3151 ⁂@lemmy.ml
    link
    fedilink
    arrow-up
    1
    ·
    34 minutes ago

    Rust

    use itertools::Itertools;
    
    fn _solve(text: String) -> (i32, i32) {
        let counts = text
            .lines()
            .counts()
            .into_iter()
            .sorted_by(|(_, v), (_, v2)| Ord::cmp(v, v2));
    
        (
            counts
                .clone()
                .rev()
                .take(3)
                .map(|(k, _)| k.parse::<i32>().unwrap())
                .product(),
            counts
                .take(3)
                .map(|(k, _)| k.parse::<i32>().unwrap())
                .product(),
        )
    }
    

    I would love any tips for more clever ways to do this!

  • morrowind@lemmy.ml
    link
    fedilink
    arrow-up
    3
    ·
    14 hours ago

    ProseScript

    day one involves getting the product of the most and least common three ids in a list.
    
    start by reading the input
    Const FS = require("fs")
    Const Input = FS.readFileSync("input.txt", "utf-8");
    
    define a handy Function to get the Product of ([Number, Number][] an Array of pairs) {
      Return Array.reduce(Accumulator [Value] => Accumulator * Value, initial value of 1)
    }
    
    
    Function Solve lets us pass in th real or test (String Input) {
    
      to figure how common each id is, we need a 
      Const Tally of each = which we'll store in a New Map< from the id Number, to its count Number >()
    
      For Const Line Of Input.trim().split(on newlines including windows carriage returns /\r?\n/) {
        Const N = Number(convert Line)
    
        Tally.set(the count at N, to (Tally.get the current count at (N) ?? or start at 0) incremented + 1)
      }
    
      now to get most/least common we need them 
      Const Sorted = so [expand ...Tally into an array bc maps are unordered] then
        .sort(A B => A[1] - B[1] gives a negative when first is greater; which makes it descending)
    
      Return [
        part one: Product(Sorted.slice(0, 3)), most common
        part two: Product(Sorted.slice(-3)) least common
      ]
    };
    
    Console.log(Solve(TEST));
    Console.log(Solve(Input));
    
  • morrowind@lemmy.ml
    link
    fedilink
    arrow-up
    2
    ·
    15 hours ago

    Odin

    package main
    
    import "core:fmt"
    import "core:os"
    import "core:strings"
    import "core:strconv"
    import "core:slice"
    
    Entry :: struct { value, count: int }
    
    main :: proc() {
    	bytes, err := os.read_entire_file("input.txt", context.allocator)
    	assert(err == nil)
    	defer delete(bytes)
    
    	input := string(bytes)
    
    	counts := make(map[int]int)
    	defer delete(counts)
    
    	for num in strings.split_lines(input) {
    		converted := strconv.parse_int(num) or_continue
    		counts[converted] += 1
    	}
    
    	entries := make([dynamic]Entry)
    	defer delete(entries)
    
    	for key, val in counts { append(&entries, Entry{key, val}) }
    
    	slice.sort_by(entries[:], proc(a, b: Entry) -> bool {
    		return a.count > b.count 
    	})
    
    	fmt.println("Entries:", entries)
    
    	prod := 1
    	for e in entries[:3] {prod *= e.value}
    	fmt.println("Part 1:", prod)
    
    	prod = 1
    	for e in entries[len(entries)-3:] {prod *= e.value}
    	fmt.println("Part 2:", prod)
    }
    
  • morrowind@lemmy.ml
    link
    fedilink
    arrow-up
    2
    ·
    19 hours ago

    Roc

    import "input.txt" as input : Str
    
    main! = |_args| {
    	nums = input.split_on("\n").map_try(U64.from_str)?
    
    	tallies = nums.fold(Dict.empty(),	|tally, num| {
    		tally.update(num, |entry| match entry {
    				Ok(count) => Ok(count + 1)
    				Err(_) => Ok(1)
    			}
    		)
    	})
    
    	.to_list().sort_by(|a| a.1)
    
    	dbg tallies.take_last(3) .map(|t| t.0).fold(1, |acc, num| acc * num)
    	dbg tallies.take_first(3).map(|t| t.0).fold(1, |acc, num| acc * num)
    
    	Ok({})
    }
    
  • codeinabox@programming.dev
    link
    fedilink
    English
    arrow-up
    4
    ·
    1 day ago

    I decided to solve it in Python, which was easier than I expected because of Counter.

    import sys
    from collections import Counter
    
    with open(sys.argv[1], encoding="utf-8") as f:
        counts = Counter()
    
        while True:
            id = f.readline().rstrip()
            if id == "":
                break
    
            counts[id] += 1
    
        initial = 1
        for id, _ in counts.most_common(3):
            initial = initial * int(id)
    
        print(initial)
    
  • Hugh@programming.dev
    link
    fedilink
    arrow-up
    11
    ·
    edit-2
    1 day ago

    Bash

    Maybe this is cheating a little to use GNU coreutils

    sort input | uniq -c | sort -r | head -n 3
    

    gives you the three most frequent IDs and their frequency.

    edit: part2 solution:

    sort input | uniq -c | sort -r | tail -n 3
    

    :)

  • morrowind@lemmy.ml
    link
    fedilink
    arrow-up
    2
    ·
    edit-2
    14 hours ago

    Crystal

    (more coming soon, I haven’t had time to do it in a new language yet!)

    input = File.read("input.txt")
    
    tallies = input.lines.map(&.to_i).tally.to_a.sort!{|a, b| b[1] <=> a[1]}
    
    p tallies[0..2].product(&.[0]) # part 1
    
    p tallies[-3..].product(&.[0]) # part 2
    
  • mykl@lemmy.world
    link
    fedilink
    arrow-up
    6
    ·
    edit-2
    1 day ago

    Uiua

    A nice gentle start… [edit: slightly tweaked to save 6 operations]

    "57\n57\n55\n57\n76\n78\n57\n45\n43\n78\n43\n76\n43\n78\n57\n45\n57\n76\n43\n43\n76"
    ⋕⊜□⊸≠@\n   # Split lines.
    ⊕⊃⧻⊢⊸⊛     # Group by occurrences.
    ∩/×∩↙₃⊸⇌⊏⍏ # Sort, take first, last three.
    
    • eta@feddit.org
      link
      fedilink
      English
      arrow-up
      3
      ·
      1 day ago

      How do you actually write this? Do have all symbols mapped to your keyboard somehow or do you have a list with symbols and copy them one symbol at a time?

      • mykl@lemmy.world
        link
        fedilink
        arrow-up
        3
        ·
        1 day ago

        There’s a very good online editor at the Uiua website, and an excellent extension for Visual Studio.

        They both allow you to type mnemonics for the symbols and common idioms, so that first line would be typed as parse partition box by ne @\n or pars pbbn @\n if you’re really in a hurry.

  • VegOwOtenks@lemmy.world
    link
    fedilink
    arrow-up
    5
    ·
    1 day ago

    Shell

    Almost too easy, but I won’t be doing shell for the upcoming days.

    Part 1

    sed '/^$/d' input | sort | uniq -c | sort -d | tail -n 3 | cut -f 8 -d ' ' | paste -sd* | bc
    

    Part 2

    sed '/^$/d' input | sort | uniq -c | sort -d | head -n 3 | cut -f 8 -d ' ' | paste -sd* | bc
    
  • Hugh@programming.dev
    link
    fedilink
    arrow-up
    4
    ·
    edit-2
    1 day ago

    Lua

    My first time ever using lua.

    Usage: lua frequencies.lua < input

    local frequencies = {}
    local pt1 = 1
    local pt2 = 1
    local uniq = 0
    
    -- initialise table of zeros. Assumes all IDs are three digit nums
    for i = 1, 999 do
            table.insert(frequencies, {id = i, frequency = 0})
    end
    
    while true do
            local line = io.read("*number")
            if line == nil then break end
            frequencies[line].frequency = frequencies[line].frequency + 1
            if frequencies[line].frequency == 1 then
                    uniq = uniq + 1
            end
    end
    
    print("Number of unique IDs is: " .. uniq)
    
    local function compareDescending(a, b)
            return a.frequency > b.frequency
    end
    
    table.sort(frequencies, compareDescending)
    
    -- Get the top three
    print("Pos\tID\tfreq")
    for i = 1, 3 do
            print(i, frequencies[i].id, frequencies[i].frequency)
            pt1 = pt1 * frequencies[i].id
    end
    
    -- Get the bottom three
    for i = 1, 3 do
            j = uniq - 3 + i
            print(j, frequencies[j].id, frequencies[j].frequency)
            pt2 = pt2 * frequencies[j].id
    end
    
    print("Answer to part 1 is: " .. pt1)
    print("Answer to part 2 is: " .. pt2)
    

    edit: updated to include solution to part 2

  • Gobbel2000@programming.dev
    link
    fedilink
    arrow-up
    2
    ·
    1 day ago

    Rust

    fn solve(input: String) {
        let mut counter = FxHashMap::default();
        for l in input.lines() {
            let n: u32 = l.parse().unwrap();
            counter.entry(n).and_modify(|e| *e += 1).or_insert(1);
        }
        let mut ids: Vec<u32> = counter.keys().copied().collect();
        ids.sort_by_key(|id| -counter[id]);
        println!("Part 1: {}", ids.iter().take(3).product::<u32>());
        println!("Part 2: {}", ids.iter().rev().take(3).product::<u32>());
    }
    
  • CameronDev@programming.devOPM
    link
    fedilink
    arrow-up
    5
    ·
    1 day ago

    Rust

            let input = include_str!("../../input/2026/day_1.txt");
            let mut recipes = HashMap::new();
            input
                .split('\n')
                .map(|line| line.parse::<u32>().unwrap())
                .for_each(|value| {
                    *recipes.get_or_set_with_mut(value, || 0) += 1;
                });
    
            let mut recipes = recipes.into_iter().collect::<Vec<(u32, i32)>>();
            recipes.sort_by_key(|a| -a.1);
    
            let result = recipes[0].0 * recipes[1].0 * recipes[2].0;
            println!("{result}");
    

    Probably non-optimal, but still 1ms, so good enough for me.

    Kinda bizarrely easy second task, only had to change one character.

    • CameronDev@programming.devOPM
      link
      fedilink
      arrow-up
      2
      arrow-down
      2
      ·
      1 day ago

      For shits and giggles I tried it on my local LLM agent, it took a small amount of prompting, but solved it in about 5 mins.

      The best part is this:

      It so confidently multiplied 3 numbers together and got the answer wrong… first set was correct somehow, second was completely hallucinated.

  • eco_game@discuss.tchncs.de
    link
    fedilink
    arrow-up
    4
    ·
    1 day ago

    C++

    As I’ve started learning C++, I will be doing the easier puzzles in C++ as well as my usual Kotlin. This is definitely still beginner code and less fancy than the other solution in this thread, but hey it works.

    If you see any possible improvements do let me know!

    Solution
    static std::vector<int> read_file(const std::string_view path) {
        const fs::path file{path};
    
        std::ifstream in{file};
        if (!in) {
            std::cerr << "cannot read " << file << '\n';
            return {};
        }
    
        std::vector<int> out;
        int number;
        while (in >> number) {
            out.push_back(number);
        }
    
        if (!in.eof()) {
            std::cerr << "invalid input or read error in " << file << '\n';
        }
    
        return out;
    }
    
    static std::unordered_map<int, long> get_counts(const std::vector<int>& numbers) {
        std::unordered_map<int, long> map;
        for (const int number : numbers) {
            ++map[number];
        }
        return map;
    }
    
    static long part_1(const std::vector<std::pair<int, long>>& counts) {
        long prod{1};
        for (std::size_t i{0}; i < 3; ++i) {
            prod *= counts[i].first;
        }
        return prod;
    }
    
    static long part_2(const std::vector<std::pair<int, long>>& counts) {
        const std::size_t len{std::size(counts)};
        long prod{1};
        for (std::size_t i{len - 1}; i > len - 4; --i) {
            prod *= counts[i].first;
        }
        return prod;
    }
    
    int main() {
        const std::vector nums{read_file("/home/eco/code/aoc_cpp/res/day01.txt")};
        const std::unordered_map counts{get_counts(nums)};
    
        const auto comp = [](const std::pair<int, long>& a, const std::pair<int, long>& b) {
            return a.second > b.second;
        };
    
        std::vector<std::pair<int, long>> counts_vector;
        counts_vector.assign(counts.begin(), counts.end());
        std::sort(counts_vector.begin(), counts_vector.end(), comp);
    
        std::cout << "part 1: " << part_1(counts_vector) << '\n';
        std::cout << "part 2: " << part_2(counts_vector) << '\n';
    
        return 0;
    }
    
  • obliviousdusk@lemmy.zip
    link
    fedilink
    arrow-up
    4
    ·
    1 day ago

    Rust

    fn parts(input: &str) -> (String, String) {
        let counts = input
            .split(|x| x == '\n')
            .flat_map(|numst| numst.parse::<u64>().ok())
            .counts();
    
        let part1: u64 = counts
            .iter()
            .k_largest_by_key(3, |x| x.1)
            .map(|x| x.0)
            .product();
        let part2: u64 = counts
            .iter()
            .k_smallest_by_key(3, |x| x.1)
            .map(|x| x.0)
            .product();
        (part1.to_string(), part2.to_string())
    }