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

  • VegOwOtenks
    link
    fedilink
    arrow-up
    4
    ·
    31 minutes 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
    2
    ·
    3 minutes 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.

  • mykl
    link
    fedilink
    arrow-up
    4
    ·
    edit-2
    2 minutes ago

    Uiua

    A nice gentle start… [edit: slightly tweaked to save 3 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 occurences.
    ∩/×∩⌟↙⊸¯ 3⊏⍏ # Sort, take first, last three.
    
    • eta@feddit.org
      link
      fedilink
      English
      arrow-up
      2
      ·
      55 minutes 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
        link
        fedilink
        arrow-up
        2
        ·
        39 minutes 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.

  • eta@feddit.org
    link
    fedilink
    English
    arrow-up
    3
    ·
    edit-2
    11 minutes ago

    Elixir

    First I tried to manually assemble a list with the IDs and their amounts but then found out there is a built in function for that.

    solution
    #!/usr/bin/env elixir
    
    require Logger
    
    defmodule AOC do
    
    def part1(filename) do
    	ids =
    		File.read!(filename)
    		|> String.trim()
    		|> String.split("\n")
    		|> Enum.map(fn x -> String.to_integer(x) end)
    		|> Enum.frequencies()
    	[p1, p2, p3 | _rest] = Enum.sort_by(ids, fn {_k,v} -> -v end)
    	{p1, p2, p3}
    end
    
    def part2(filename) do
    	ids =
    		File.read!(filename)
    		|> String.trim()
    		|> String.split("\n")
    		|> Enum.map(fn x -> String.to_integer(x) end)
    		|> Enum.frequencies()
    	[p1, p2, p3 | _rest] = Enum.sort_by(ids, fn {_k,v} -> v end)
    	{p1, p2, p3}
    end
    
    end # module
    
    {p1, p2, p3} = AOC.part1("input/day01Test.txt")
    res = elem(p1,0)*elem(p2,0)*elem(p3,0)
    if res != 186276, do: raise "result should be 186276 but is #{res}"
    {p1, p2, p3} = AOC.part1("input/day01Input.txt")
    res = elem(p1,0)*elem(p2,0)*elem(p3,0)
    Logger.info("Part 1: #{res}")
    
    {p1, p2, p3} = AOC.part2("input/day01Test.txt")
    res = elem(p1,0)*elem(p2,0)*elem(p3,0)
    if res != 193050, do: raise "result should be 193050 but is #{res}"
    {p1, p2, p3} = AOC.part2("input/day01Input.txt")
    res = elem(p1,0)*elem(p2,0)*elem(p3,0)
    Logger.info("Part 2: #{res}")
    
  • Camille@lemmy.ml
    link
    fedilink
    arrow-up
    2
    ·
    2 hours ago

    Hare

    Another year, another AOC! This year I’m doing it in Hare, because why not. As usual I started by writing a small library to fetch the day’s input and to run each puzzle just by sending a function as callback. I don’t see the point of sharing it unless people want to see the code.

    part 1
    type number_list = [](uint, uint);
    
    fn cmpnblist(a: *opaque, b: *opaque) int = {
    	const lhs = (*(a: *(uint, uint))).1: int;
    	const rhs = (*(b: *(uint, uint))).1: int;
    
    	return rhs - lhs;
    };
    
    fn up(list: *number_list, val: uint) void = {
    	let length = len(list);
    	for (let idx = 0z; idx < length; idx += 1) {
    		const (v, count) = list[idx];
    		if (v == val) {
    			list[idx] = (v, count + 1);
    			return;
    		};		
    	};
    
    	append(list, (val, 1))!;
    };
    
    fn part1(scan: *bufio::scanner) (int | done) = {
    	let numbers: number_list = alloc([], 0)!;
    	defer free(numbers);
    
    	for (true) {
    		match (bufio::read_line(scan)) {
    		case io::EOF => break;
    		case let e: io::error => {
    			log::printfln("error: {}", io::strerror(e));
    			return done;
    		};
    
    		case let buf: []u8 => {
    			const line = strings::fromutf8(buf)!;
    			const val = strconv::stou(line)!;
    			up(&numbers, val);	
    		};
    		};
    	};
    
    	sort::sort(numbers, size((uint, uint)), &cmpnblist)!;
    	const highest3 = numbers[0..3];
    	const factor = 1u;
    
    	for (let (v, _) .. highest3) {
    		factor *= v;
    	};
    
    	return factor: int;
    };
    
    part 2
    fn part2(scan: *bufio::scanner) (int | done) = {
    	let numbers: number_list = alloc([], 0)!;
    	defer free(numbers);
    
    	for (true) {
    		match (bufio::read_line(scan)) {
    		case io::EOF => break;
    		case let e: io::error => {
    			log::printfln("error: {}", io::strerror(e));
    			return done;
    		};
    
    		case let buf: []u8 => {
    			const line = strings::fromutf8(buf)!;
    			const val = strconv::stou(line)!;
    			up(&numbers, val);	
    		};
    		};
    	};
    
    	sort::sort(numbers, size((uint, uint)), &cmpnblist)!;
    	const length = len(numbers);
    	const lowest3 = numbers[length-3..length];
    	const factor = 1u;
    
    	for (let (v, _) .. lowest3) {
    		factor *= v;
    	};
    
    	return factor: int;
    };
    
  • Ananace@lemmy.ananace.dev
    link
    fedilink
    arrow-up
    2
    ·
    2 hours ago

    C#

    Decided to go for just writing some basic C#, to keep that knowledge up-to-date.

    List<(int,int)> bins = new List<(int,int)>();
    
    public void Load(string file) {
      var numbers = File.ReadAllLines(file)
        .Select(line => int.Parse(line))
        .ToList();
      bins = numbers
        .GroupBy(n => n)
        .Select(kv => (kv.Key, kv.Count()))
        .OrderBy(bin => bin.Item2)
        .ToList();
    }
    
    public void Part1() {
      var threeLargest = ((IEnumerable<(int,int)>)bins)
        .Reverse()
        .Take(3)
        .Aggregate((1,1), (a, b) => (a.Item1 * b.Item1, 1))
        .Item1;
      Console.WriteLine($"Part 1: {threeLargest}");
    }
    
    public void Part2() {
      var threeSmallest = bins
        .Take(3)
        .Aggregate((1,1), (a, b) => (a.Item1 * b.Item1, 1))
        .Item1;
      Console.WriteLine($"Part 2: {threeSmallest}");
    }
    
  • VegOwOtenks
    link
    fedilink
    arrow-up
    4
    ·
    edit-2
    3 hours ago

    Haskell

    module Main where
    import Data.List (sort, sortOn)
    import Data.Ord (Down(Down))
    import Control.Arrow ((&&&))
    import Data.List.NonEmpty (groupBy1)
    import qualified Data.List.NonEmpty as NE
    
    interactLn :: (String -> String) -> IO ()
    interactLn f = interact f *> putStrLn ""
    
    main :: IO ()
    main = interactLn $ show . (part1 &&& part2) . counts . sort . map read . init . lines
    
    mkPart f = product . map snd . take 3 . sortOn f
    
    part1, part2 :: [(Int, Int)] -> Int
    part1 = mkPart Down
    part2 = mkPart id
    
    counts :: Eq a => [a] -> [(Int, a)]
    counts = map (length &&& NE.head) . NE.group
    

    Apparently, my part 2 is wrong? I double-checked with a second solution from here but it’s the same result. I’d like to ask for help, but since I’m not allowed to share my input I’m a bit at a loss.

      • VegOwOtenks
        link
        fedilink
        arrow-up
        3
        ·
        2 hours ago

        I would like to compare w/ solutions here but it seems like most cannot be run and require a framework.

        • eco_game@discuss.tchncs.de
          link
          fedilink
          arrow-up
          3
          ·
          edit-2
          2 hours ago

          I’d recommend going to github / codeberg / …, searching for aoc tags and filter by python. Python usually runs best without needing a project surrounding it, if you want to test your input.

          Edit: see here

          • VegOwOtenks
            link
            fedilink
            arrow-up
            2
            ·
            33 minutes ago

            Thank you, I managed to resolve it by pasting the correct number x.x

          • VegOwOtenks
            link
            fedilink
            arrow-up
            2
            ·
            33 minutes ago

            Thank you, I managed to resolve it by pasting the correct number x.x

  • obliviousdusk@lemmy.zip
    link
    fedilink
    arrow-up
    3
    ·
    3 hours 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())
    }
    
  • hades@programming.devM
    link
    fedilink
    arrow-up
    3
    ·
    3 hours ago

    Rust

    #[derive(Default)]
    pub struct Day1Solver {
        crate_by_encounters: Vec<(i64, i64)>,
    }
    
    impl Solver for Day1Solver {
        fn presolve(&mut self, input: &str) {
            let input: Vec<_> = input
                .trim()
                .lines()
                .map(|line| line.parse().unwrap())
                .collect();
            let mut encounter_map: HashMap<_, i64> = HashMap::new();
            for crate_id in input.iter() {
                *encounter_map.entry(crate_id).or_default() += 1;
            }
            let mut crates_by_encounters: Vec<_> = encounter_map
                .drain()
                .map(|(&crate_id, count)| (count, crate_id))
                .collect();
            crates_by_encounters.sort();
            self.crate_by_encounters = crates_by_encounters;
        }
        fn solve_part_one(&mut self) -> String {
            self.crate_by_encounters
                .iter()
                .rev()
                .take(3)
                .fold(1, |a, (_, b)| a * b)
                .to_string()
        }
        fn solve_part_two(&mut self) -> String {
            self.crate_by_encounters
                .iter()
                .take(3)
                .fold(1, |a, (_, b)| a * b)
                .to_string()
        }
    }
    
  • eco_game@discuss.tchncs.de
    link
    fedilink
    arrow-up
    2
    ·
    3 hours 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;
    }
    
  • eco_game@discuss.tchncs.de
    link
    fedilink
    arrow-up
    3
    ·
    edit-2
    24 minutes ago

    Kotlin

    Day 1 and I already miss numpy. Nothing fancy here, just constructing a map counting the occurrences and sorting by its values.

    Edit:
    I figured out that Kotlin has a .groupingBy {} function, which can replace manually constructing the map. I changed the code on Codeberg, the solution here is still my initial one.

    Solution
    class Day01 : Puzzle {
    
        private lateinit var ids: List<Int>
        private lateinit var counts: Map<Int, Long>
    
        override fun readFile() {
            val input = readInputFromFile(2026, 1, false)
            ids = input.lines().filter { it.isNotBlank() }.map{ it.toInt() }
            counts = getCounts(ids)
        }
    
        override fun solvePartOne(): String {
            return counts.toList()
                .sortedByDescending { (_, v) -> v }
                .take(3)
                .map { (k, _) -> k }
                .reduce { a, b -> a * b }
                .toString()
        }
    
        override fun solvePartTwo(): String {
            return counts.toList()
                .sortedBy { (_, v) -> v }
                .take(3)
                .map { (k, _) -> k }
                .reduce { a, b -> a * b }
                .toString()
        }
    
        private fun getCounts(ids: List<Int>): Map<Int, Long> {
            val counts = mutableMapOf<Int, Long>()
            for (id in ids) {
                if (id in counts) {
                    counts[id] = counts[id]!! + 1
                } else {
                    counts[id] = 1
                }
            }
            return counts
        }
    }
    

    full code on Codeberg

  • CameronDev@programming.devOPM
    link
    fedilink
    arrow-up
    2
    ·
    4 hours 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
      1
      ·
      1 hour 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.

  • Ismail@programming.dev
    link
    fedilink
    arrow-up
    4
    ·
    5 hours ago

    TXR

    The 'hist-sort' function call does most of the work here, creating an association list of (id . freq) pairs in decreasing order of frequency:

    @(next "01-input")
    @(collect)
    @  ids
    @(end)
    @;;
    @(bind freqs @(hist-sort [map int-str ids]))
    @;;
    @(output)
    1: @[prod (take 3 freqs) car]
    2: @[prod (last freqs 3) car]
    @(end)
    
  • obdurant@lemmy.zip
    link
    fedilink
    arrow-up
    4
    ·
    6 hours ago

    #Zig

    const std = @import("std");
    const input = @embedFile("./input");
    
    pub fn main() !void {
        var total: u64 = 1;
        const ally = std.heap.page_allocator;
        var id_iter = std.mem.splitScalar(u8, input, '\n');
        var id_hash = std.AutoHashMap(u16, u16).init(ally);
        defer id_hash.deinit();
        while (id_iter.next()) |line| {
            const trimmed_line = std.mem.trim(u8, line, " \r");
            if (trimmed_line.len == 0) continue;
            const id = try std.fmt.parseInt(u16, trimmed_line, 10);
            const entry = try id_hash.getOrPut(id);
            if (entry.found_existing) {
                entry.value_ptr.* += 1;
            } else {
                entry.value_ptr.* = 1;
            }
        }
    
        for (0..3) |_| {
            var id: u16 = undefined;
            var highest: u16 = 0;
            var entry_iterator = id_hash.iterator();
            while (entry_iterator.next()) |pair| {
                if (pair.value_ptr.* > highest) {
                    highest = pair.value_ptr.*;
                    id = pair.key_ptr.*;
                }
            }
            total *= id;
            const trimmed = id_hash.remove(id);
            if (trimmed == false) std.debug.panic("halp", .{});
        }
        std.debug.print("\n{d}\n", .{total});
    }
    
    • obdurant@lemmy.zip
      link
      fedilink
      arrow-up
      3
      ·
      6 hours ago

      i spent quite some time confusedly poking at my parsing code before i realized i was splitting on ‘\n’ and there were still hidden ‘\r’ chars in the lines since I was on my work laptop.

      I haven’t done much with hash maps or sorting in Zig yet. After I sleep I might find some time tomorrow see what a better approach than iterating over the entries three times might look like, but I just wanted to squeeze something out before bed.

  • janAkali@programming.dev
    link
    fedilink
    arrow-up
    5
    ·
    6 hours ago

    Nim

    Probably one of the easiest first days in AOC history.

    Solved with HashTable -> sorting -> sequence
    Runtime: 280 μs

    proc solve(input: string): AOCSolution[int, int] =
      var cnt: CountTable[int]
      for line in input.splitLines():
        cnt.inc parseInt line
      cnt.sort()
      let s = cnt.keys.toseq()
      result.part1 = s[0] * s[1] * s[2]
      result.part2 = s[^1] * s[^2] * s[^3]
    

    Full solution at Codeberg: solution.nim

    • CameronDev@programming.devOPM
      link
      fedilink
      arrow-up
      4
      ·
      4 hours ago

      I thought you were exagerating about the easiness, because normally day 1 is easy, but being able to change a single character to solve pt2 was unusually easy. No real twist at all.

      • addie@feddit.uk
        link
        fedilink
        arrow-up
        3
        ·
        3 hours ago

        My favourite AoC challenges are the ones where part 1 is relatively straightforward, but part 2 requires some algorithmic insight or forces you to learn something new in order to complete it in a reasonable amount of time.

        I think all the people in this thread who have responded so far will be coding enthusiasts, and this is just a warm-up. Yes, you can solve it by resorting the list in the opposite direction. Or you can be a bit more efficient and reuse the same list, which requires you to do reverse iteration and risk off-by-one errors, which we all had to learn once.

        Back when it was ‘four weeks of AoC’, I used to mentally divide up the weeks into:

        1. Iteration solutions
        2. Recursion
        3. Dynamic programming
        4. Crazy shit

        … and looking at the stats, the drop-off in completion rate for the first problem that needed recursion was quite stark. So yeah, let’s start off with a couple of puzzles for everyone.

        • CameronDev@programming.devOPM
          link
          fedilink
          arrow-up
          2
          ·
          3 hours ago

          Definitely nice to have a warm up, but pt2 was just too easy IMO.

          I like the ones where pt 1 can be solved trivially, but in order to do pt2, the logic or approach needs to be completely flipped.

          Slapping memoisation on a trivial solution just feels a bit boring after a while, even if it is cool

    • addie@feddit.uk
      link
      fedilink
      arrow-up
      4
      ·
      6 hours ago

      C++

      I’d have to check back through them, but they tend to be pretty easy on the first day; let the people that are using Excel get a win. 12 days again this year, so they should ramp up pretty quick - I actually preferred that last year, keep it short and sweet, no filler.

      Solved by counting the entries in a hash map, then sorting it. 90 microseconds.

      auto parts(const std::vector<int>& input) {
        auto count = boost::unordered_flat_map<int, int>{1000};
        for (const auto& entry : input)
          ++count[entry];
        auto sort = std::vector<std::pair<int, int>>{count.begin(), count.end()};
        std::sort(sort.begin(), sort.end(), [](auto& a, auto& b) {
          return a.second > b.second;
        });
        auto part1 = sort[0].first * sort[1].first * sort[2].first;
        auto size = sort.size();
        auto part2 =
          sort[size - 1].first * sort[size - 2].first * sort[size - 3].first;
        return std::pair{part1, part2};
      }
      
        • addie@feddit.uk
          link
          fedilink
          arrow-up
          3
          ·
          2 hours ago

          It’s about fifty times faster, since it doesn’t make the specification-required mistakes in the standard one. (Specifically, iteration in constant time. The Boost one is ‘always faster’, but not constant. Constant time requires maintaining a separate linked list of all entries, which wastes time and memory.)

          For this; no, makes no difference. The problem space is so small that the standard maps are quite fast enough. Just force it habit to never use them.