30

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

top 50 comments
sorted by: hot top new old
[-] Unusable3151@lemmy.ml 1 points 4 hours 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!

[-] shape_warrior_t@programming.dev 1 points 1 hour ago

Parsing into a number as the final operation before taking the product is... certainly an interesting decision, one that only works because the IDs are all the same length so lexicographic comparison coincides with ordinary integer comparison.

If you're already using itertools, it has k_largest_by_key and k_smallest_by_key methods (see this other Rust solution). In general, Rust itertools has a great variety of helpful functions. If you need to do some generic algorithmic task involving an iterator, chances are you can find it in the docs.

[-] CameronDev@programming.dev 1 points 3 hours ago

sort_by_key instead of sorted_by might simplify it some more, but thats a pretty clean solution as is.

[-] morrowind@lemmy.ml 3 points 17 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 2 points 18 hours ago* (last edited 18 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 2 points 22 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({})
}
[-] Hugh@programming.dev 11 points 1 day ago* (last edited 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

:)

[-] CameronDev@programming.dev 2 points 1 day ago

Not cheating at all, its as valid a tool as any other

[-] codeinabox@programming.dev 4 points 1 day ago* (last edited 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)
[-] CameronDev@programming.dev 9 points 1 day ago
[-] mykl@lemmy.world 2 points 1 day ago

Looking forward to seeing how this goes!

[-] CameronDev@programming.dev 3 points 1 day ago

im probably not gonna keep doing excel, this one was just easy enough to pull off. I think I did one day last year as well.

[-] morrowind@lemmy.ml 2 points 1 day ago* (last edited 17 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 6 points 1 day ago* (last edited 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 3 points 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 3 points 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 3 points 1 day ago

This is the compiled form, you write some human-readable strings and they are automatically transformed for brevity. You can try it on https://www.uiua.org/pad

[-] VegOwOtenks@lemmy.world 5 points 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 4 points 1 day ago* (last edited 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 2 points 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.dev 5 points 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.dev 0 points 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 4 points 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 4 points 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())
}
[-] shape_warrior_t@programming.dev 2 points 19 hours ago

Good old itertools! Had basically the same solution, though I use str::lines instead of explicitly splitting by newline.

[-] VegOwOtenks@lemmy.world 4 points 1 day ago* (last edited 1 day 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.

[-] CameronDev@programming.dev 1 points 1 day ago

Haskell is a mystery to me, but does your pt2 work on the sample data?

[-] VegOwOtenks@lemmy.world 3 points 1 day 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 3 points 1 day ago* (last edited 1 day 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@lemmy.world 3 points 1 day ago

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

[-] CameronDev@programming.dev 2 points 1 day ago* (last edited 1 day ago)

If you DM your input to me I can test on my rust impl

[-] VegOwOtenks@lemmy.world 3 points 1 day ago

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

[-] VegOwOtenks@lemmy.world 2 points 1 day ago

Sadly yes, for both parts.

[-] ismail@programming.dev 5 points 1 day 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)
[-] Camille@lemmy.ml 3 points 1 day ago* (last edited 1 day 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;
};

[-] eta@feddit.org 3 points 1 day ago* (last edited 1 day 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}")

[-] janAkali@programming.dev 5 points 1 day ago* (last edited 1 day 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.dev 5 points 1 day 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 5 points 1 day 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.dev 3 points 1 day 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 4 points 1 day 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};
}
[-] eco_game@discuss.tchncs.de 1 points 1 day ago

Is there any benefit of using the boost map instead of a standard std one?

[-] addie@feddit.uk 3 points 1 day 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.

[-] eco_game@discuss.tchncs.de 2 points 1 day ago

Ah ok interesting, thanks. My C++ lecture hasn't touched on external? libraries yet.

[-] obdurant@lemmy.zip 4 points 1 day ago* (last edited 1 day 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 3 points 1 day 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.

[-] hades@programming.dev 3 points 1 day 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 3 points 1 day ago* (last edited 1 day 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

[-] cabhan@discuss.tchncs.de 2 points 1 day ago

Your code looks almost identical to mine, except I used getOrDefault to avoid the if in getCounts :)

I assumed there was something like groupingBy, but didn't actually find it. Good to know for the future!

[-] eco_game@discuss.tchncs.de 1 points 1 day ago

The grouping function actually wasn't on my mind at all. Only when I saw it in a C# solution in this thread I realized surely Kotlin must have something like that too...

this post was submitted on 01 Dec 2026
30 points (100.0% liked)

Advent Of Code

1262 readers
48 users here now

An unofficial home for the advent of code community on programming.dev! Other challenges are also welcome!

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.

Everybody Codes is another collection of programming puzzles with seasonal events.

EC 2025

AoC 2026

Solution Threads

M T W T F S S
1 2 3 4 5 6
7 8 9 10 11 12

Visualisations Megathread

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 3 years ago
MODERATORS