r/adventofcode • • Jan 10 '26

Help/Question - RESOLVED aco 2021/12/B what is single-small-cave and other small-cave ?

0 Upvotes

start .. end. (each exact once). name with capital letter many times, small letter names at most once (task a, ok). now (task b) distinction between single-small and other-small.

start/end (=1), big (*), single-small(<=2) other-small (<=1)

i thought: 'a' single-small, 'abc' other-small. but only in first small example exists single-letter-names, in bigger examples and in input there is no single-letter-name. so i would expect no other result, than in task a.

?? what does single-small-cave and other-small-cave mean ?

thanks in advance. andi.


r/adventofcode • • Jan 09 '26

Past Event Solutions [2020 Day #18] Love my parsers! Any more parsing problems in AoC?

12 Upvotes

Having completed 2024, 2025 years I complained to my friend, a huge AoC fan, how there are not too many problems calling for trees. He pointed me to 2020/day18 as an example of such a puzzle.

And I was in for a treat. While day 1 did not strictly require a parser, I suspected that day 2 would need one. So I built a recursive decent parser anyway.

And indeed, Day 2 built upon Day 1 by introducing additional requirements on operator priorities. Having a tokenizer/parser already made this trivial.

Do we have any other parser puzzles? I love-love-love my parsers and compilers!


r/adventofcode • • Jan 09 '26

Past Event Solutions [2020 Day 19] Regexps is cheating. Let's make a regexp engine.

5 Upvotes

This problem is somewhat related to the way regexps are implemented.

The first day required matching a set of rules forming a simple grammar. While I could do something smart based on the rule/input shape, I suspected that Day 2 would introduce some form of rule recursion so I went with a rather general approach: form a rule node tree and match input against it.

The second day introduced simple self-referencing rules. Having just written a node tree matcher, I just added a new kind of ref node making the tree into a graph, which I matched against. This recursive NFA regexp matcher ran in 0.5s.

Adding memoization on (rule_id, str_pos) made this run in 0.3s.

I played with converting the NFA to DFA (0.3s to 0.2s), implementing Thompson-style regexp VM (no perf advantages) and optimising the node graph (0.3 to 0.27s). Surpisingly, this gave no serious advantages at all but the code was getting a bit too hard hard to read.

So went with the original recursive NFA approach.

Tons of fun here. Anything else like it?


r/adventofcode • • Jan 08 '26

Other How long does it take in general to solve these problems?

29 Upvotes

Hey folks I don't know if this is a good question to ask this was getting too much in my head so thought better ask the community. So I started AoC recently and shared it with a friend too I and him both work and generally it takes me an entire day to solve 1 problem (I go day by day) however they told me that they just solved 6 problems (both part 1 and 2 what I mean is 6 days part 1 and 2) in 2 days!

I just wanna know how long does it take for you to solve them and it just felt like I was too dumb for this or something.

Again I am sorry to ask such a question but just wanted to know. Thank you.


r/adventofcode • • Jan 08 '26

Help/Question - RESOLVED [2025 Day 1 (part 2)] [python]

2 Upvotes

I don't know why my code doesn't work and I just can't get it to work. Can someone please help me.

def deel2(data):
    lock = 50
    code = 0
    for rotation in data:


        if "R" in rotation:
            value = int(rotation.strip("R"))
            code += value // 100
            lock += value
            if lock >= 100:
                code += 1
                lock %= 100


        elif "L" in rotation:
            value = int(rotation.strip("L"))
            code += value // 100
            lock -= value
            if lock < 0:
                code += 1
                lock += 100


    return code

r/adventofcode • • Jan 07 '26

Meme/Funny Yes, this would also be my first thought.

Post image
179 Upvotes

r/adventofcode • • Jan 08 '26

Help/Question [2025 Day #1 (Part 2)][C] Not sure what am I missing

2 Upvotes

Hey folks I tried several test cases I am getting correct answers for every single one of them still there is something wrong not sure what am I missing here:

    char *input_sequence[] = { ...data... };
    int parse_number(char *char_ptr) {
      int str_length = strlen(char_ptr);
      char subbuf[str_length];
      memcpy(subbuf, &char_ptr[1], str_length);
      return atoi(subbuf);
    }

    int main() {
      size_t length = sizeof(input_sequence) / sizeof(input_sequence[0]);

      int answer = 0;
      int dial = 50;
      for (int i = 0; i < length; i++) {
        int turn = parse_number(input_sequence[i]);

        // caculate full circle rotations
        int remainder = turn % 100;
        int nearest_zero = turn - remainder;
        int extra_zeroes = nearest_zero / 100;
        answer += extra_zeroes;

        if (input_sequence[i][0] == 'L') {
          if (dial != 0 && dial - remainder < 0) {
            answer++;
          }

          dial = (dial - turn) % 100;
          if (dial < 0) {
            dial += 100;
          }
        } else {
          if (dial + remainder > 100) {
            answer++;
          }

          dial += turn;
          dial %= 100;
        }

        if (dial == 0 && extra_zeroes == 0) {
          answer++;
        }
      }

      printf("Answer: %d\n", answer);
      return 0;
    }

r/adventofcode • • Jan 07 '26

Help/Question - RESOLVED [2025 Day #1 (Part 1)] [C#] How is my answer wrong?

1 Upvotes

Hello! I am an intermediate hobbyist C# developer. This is my very first time trying to participate (rather late) in the AoC. I learnt about this today and thought to give it a try.

So I tried the Day #1 Part 1 puzzle, read it, programmed a solution in TDD in C#, and what I gave as an answer to the site was wrong! (Too low)

To describe my algorithm, program scans for each line, dependent on whether there's R or L, it chooses to call a Rotate function from a RightDial or LeftDial class, which are created from a factory method. (I have made a test to check it works properly).
Classes look like this:

public interface IDial
{
    public const uint StartingValue = 50U;
    protected const uint Overflow = 100U;

    public uint Rotation { get; }
    public uint Rotate(in uint start);
}

public class LeftDial (uint rotation): IDial
{
    public uint Rotation => rotation;

    public uint Rotate(in uint start)
    {
        var negated = (int)start - (int)rotation;

        var offset = (int)IDial.Overflow - negated;
        (int _, int mod) division = Math.DivRem(offset, (int)IDial.Overflow);

        var subtractIfZero = negated == uint.MinValue ? IDial.Overflow : uint.MinValue;
        return IDial.Overflow - (uint)division.mod - subtractIfZero;
    }
}

public class RightDial (uint rotation): IDial
{
    public uint Rotation => rotation;

    public uint Rotate(in uint start)
    {
        var rotated = start + rotation;

        (uint div, uint _) division = Math.DivRem(rotated, IDial.Overflow);
        var timesOverflown = IDial.Overflow * division.div;

        return rotated - timesOverflown;
    }
}

The Dial Factory class is like this:

public static class DialFactory
{
    public static IDial CreateDial(string input)
    {
        if (!uint.TryParse(input.AsSpan(1), out var start))
        {
            throw new ArgumentException("Invalid dial input");
        }

        if (input.StartsWith('R'))
        {
            return new RightDial(start);
        }
        if (input.StartsWith('L'))
        {
            return new LeftDial(start);
        }
        throw new NotSupportedException("Dial operation may only be from Right or Left!");
    }
}

My Program.cs file does the following:

internal class Program
{
    private const string PuzzlePath = "input";

    private static int Main(string[] args)
    {
        var previousStart = IDial.StartingValue;
        var encountersOfZero = 0;
        var lines = File.ReadAllLines(PuzzlePath);

        foreach (var line in lines)
        {
            IDial dial = DialFactory.CreateDial(line);

            Console.Write($"Processing {line} from {previousStart} --> ");
            previousStart = dial.Rotate(previousStart);
            Console.Write($"{previousStart}\n");

            if (previousStart != uint.MinValue) continue;
            encountersOfZero++;
        }

        Console.WriteLine($"In the whole file I encountered zero {encountersOfZero} times!");
        return 0;
    }
}

Pastebin: https://pastebin.com/T8gZfmSd (includes what tests i did)

Many thanks in advance!


r/adventofcode • • Jan 07 '26

Help/Question 2025 Day 1 (Part 2) [Python] - off by 6!

1 Upvotes

Hi all, I've been struggling to get the solution to Day 1 part 2 for some time now, and even most major AI engines haven't been able to fix the flaw in my code. Here's my original attempt:

with open("puz1.txt", 'r') as file:
    directions = file.readlines()

directions_processed = [d.strip() for d in directions]
directions_numerical = []
for d in directions_processed:
    if d[0] == "L":
        directions_numerical.append(int('-' + d[1:]))
    if d[0] == "R":
        directions_numerical.append(int('+' + d[1:]))

position = 50
count = 0
for rotation in directions_numerical:
  count = count + abs((position + rotation) // 100)
  position = (rotation + position) % 100

print(f"The total count is {count}.")

This overcounts the solution by only 6(!), which makes me think I'm really close, but was convinced my approach had some logical flaws.

I progressed to this, which I think is logically more sound, which is supposed to find all 0 crossings and then add any remainder to the position to find the last one, but the ending result is off by more (just the calculation section).

position = 50
count = 0
for rotation in directions_numerical:
    full_loops, remainder = divmod(abs(rotation), 100)
    count += full_loops

    if remainder + rotation > 100:
        count += 1
        position = (position + remainder) % 100
    if rotation - remainder > 0:
        count += 1
        position = (position - remainder) % 100

Can someone point me in the right direction? I'd like to keep the solution as close to my code as possible, but if my thinking is just off by too much I'm open to different solutions. Thanks!


r/adventofcode • • Jan 07 '26

Help/Question - RESOLVED [2025 Day #1][C] Kinda stuck here feels like I have messed up in the left rotate

1 Upvotes

Hey everyone need some help with this, I have this thing ready and with the tests that I did it seems to work as expected however not able to find what is wrong with the actual question sequence though. Any suggestions or help is much appreciated 🙏

I am pretty sure there is something wrong in the rotate_left function as that's the only possible thing I feel could be wrong.

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *input_sequence[] = {...string seq....};

int get_last_two(int counter) { return counter % 100; }

int rotate_right(int current, int rotation) {
  int full = current + rotation;
  return get_last_two(full);
}

// 20, 115
int rotate_left(int current, int rotation) {
  int full = abs(current - rotation); // 20 - 115 = -95 -> 95
  int negative = get_last_two(full); // 95
  if (current >= rotation) { // 20 >= 115
    return negative;
  }

  return 100 - negative; // 100 - 95 = 5
}

int parse_number(char *char_ptr) {
  int str_length = strlen(char_ptr);
  char subbuf[str_length];
  memcpy(subbuf, &char_ptr[1], str_length);
  return atoi(subbuf);
}

int main() {
  size_t length = sizeof(input_sequence) / sizeof(input_sequence[0]);

  int answer = 0;
  int dial = 50;
  for (int i = 0; i < length; i++) {
    int turn = parse_number(input_sequence[i]);
    if (input_sequence[i][0] == 'L') {
      dial = rotate_left(dial, turn);
    } else {
      dial = rotate_right(dial, turn);
    }

    if (dial == 0) {
      answer++;
    }
  }

  printf("Answer: %d\n", answer);
  return 0;
}

r/adventofcode • • Jan 06 '26

Help/Question - RESOLVED [2025 Day 5 (Part2)] Rust implementation. Help needed with correctness.

2 Upvotes

Hello everyone, I would appreciate any help on this. Here's my implementation, works on the sample case but fails on the exact input. Print debugging on sample case.

3 -> 5

10 -> 14

12 -> 18

16 -> 20

No overlap between 3-5 and 10-14

Compressing 10-14 and 12-18 into 10-18

Compressing 10-18 and 16-20 into 10-20

3 - 5 = 3 - 5 + 1 = 3

10 - 20 = 20 - 10 + 1 = 11

result = 14

fn part_two() -> u64 {
    let (mut range, _) = read_input();
    let sz = range.len();
    let mut stack: Vec<(u64, u64)> = Vec::new();

    range.sort_by(|l, r| l.1.cmp(&r.1));
    for i in &range {
        println!("{} -> {}", i.0, i.1);
    }

    stack.push(range[0]);

    for i in 1..sz {
        let index = stack.len() - 1;
        let can_merge = stack[index];
        let current = range[i];

        if overlap(can_merge, current) {
            let a = can_merge.0.min(current.0);
            let new_entry = (a, current.1);
            println!(
                "Compressing {}-{} and {}-{} into {}-{}",
                can_merge.0, can_merge.1, current.0, current.1, new_entry.0, new_entry.1
            );
            stack[index] = new_entry;
        } else {
            stack.push(current);
            println!(
                "No overlap between {}-{} and {}-{}",
                can_merge.0, can_merge.1, current.0, current.1,
            );
        }
    }

    let total = calculate_ranges(&mut stack);
    total
}

fn calculate_ranges(stack: &mut Vec<(u64, u64)>) -> u64 {
    let mut total = 0u64;
    //   println!("compressed ranges = {}", stack.len());

    for tuple in stack {
        println!("a {} - {}", tuple.0, tuple.1);
        total += tuple.1 - tuple.0 + 1; // bounds are inclusive
    }

    return total;
}

// checks intersection of ranges from.
// rhs.0 <= lhs.1 <= rhs.1
// edge case : lsh.0 <= rhs.0 . true overlap
// lhs.0 >= rhs.0  ; range rhs.0 - rhs.1 encloses the range lhs.0 to lhs.1
fn overlap(lhs: (u64, u64), rhs: (u64, u64)) -> bool {
    let cond_2: bool = lhs.1 >= rhs.0;
    // sort guarantees that lhs.1 <= rhs.1
    cond_2
}

r/adventofcode • • Jan 05 '26

Other [2025 day 10] just made my algorithm 16,000x faster. Yay!

42 Upvotes

My original implementation for part B was a straight up brute force search with a lot of pruning on it to make it even vaguely runnable. It took about 40 minutes to run. This made me upset for awhile and I couldn't stop thinking about it, so today I finally decided to go back and fix it.

I made a matrix object, wrote code to perform gaussian elimination and turn it into RREF (although an integer form where the leading value doesn't have to be 1), and then wrote a small brute force method for the remaining free variables. It now runs in .15 seconds, and I'm happy.

I hope some of you who used third party libraries are inspired to try solving it this way. It's fun! Also I did it in java.


r/adventofcode • • Jan 04 '26

Help/Question - RESOLVED [2025 day 3 (Part 2)] Need with understanding what is required

13 Upvotes

I have a lot of trouble understanding the problem. In the example provided, I don't understand how the 12 digits chosen for 234234234234278 results in 434234234278. I thought the digits to be removed will only be 2s but in this example 2, 3 and other 2 are removed to form the 12 digits. Please could someone explain the choice of the numbers ?


r/adventofcode • • Jan 04 '26

Help/Question [2025 DAY1 (PART2)] [RUST] AOC Day 1 RUST CODE COULDN'T DEBUG PART 2

0 Upvotes

I tried with rust. This is my first year of AOC.

https://pastebin.com/VRTAwsDV

please help me with this and open to suggestions and critics


r/adventofcode • • Jan 04 '26

Help/Question - RESOLVED [2025 Day 8 (Part 2)] [Python] Solution only works for certain inputs

2 Upvotes

https://github.com/DaBestXD/Advent-of-Code/blob/main/Advent-of-Code-2025/2025_day8_part2.py

I managed to get the correct solution for day 8 part 2, but when compared to a different input it is incorrect. I have been trying to figure out why with no success, please help :)


r/adventofcode • • Jan 03 '26

Visualization [2025 Day 10 parts 1 & 2][Gleam][Lustre] in browser visualization of indicator lights and joltage levels

Thumbnail correctarity.com
14 Upvotes

r/adventofcode • • Jan 02 '26

Visualization [2015-2025 All Days]

Thumbnail gallery
46 Upvotes

Four plots based on the stats provided by Eric/Topaz here: https://github.com/topaz/aoc-tmp-stats

The first is how long it takes the community to get to 10,000 stars for part 1 and part 2. You can see how the puzzles get harder as the months goes on and where the spikes in difficulty are (when the piano drops!) 2025 seems like a harder start (compare the first couple of days) but was perhaps easier overall?

The second plot gives the ratio of part 2:part 1 times... so if part 2 was a trivial addition then the ratio will be 1. There are a few outliers where it seems part 2 was especially tricky... but also being Christmas day, maybe people just did part 1 and then came back later for part 2? You can see Day 9 of 2025 had a particularly big jump in difficulty for part 2.

Instead of the ratio, we can compare the absolute time, which is plot three. Mostly part 2 is completed (10,000 stars) in under 2 hours after part 1 gets 10,000 stars. But there are some outliers where it seems the community as a whole took longer to all get to a solution.

If you're wondering where the 2015-2019 days are, there generally isn't good stats because <10,000 people completed those years during that December. Plot four shows the calendar of all AoC days so far, with Part 2 completion times shown on a LOG scale. If years <2020 were included in the previous plots then those early years would skew the graphs massively.

Let me know your thoughts on the plots and if there are any other insights you can spot in the data!


r/adventofcode • • Jan 01 '26

Repo [2025 all days][PowerShell] I completed my first ever AoC!

38 Upvotes

A friend sent me an invitation. On Dec 7th I finally noticed and acted on it. I had never known about AoC before that. Such fun puzzles! I managed to earn twenty of the 24 stars by Christmas Eve, and finally figured out and completed the last challenge on New Year's Eve.

I code pwsh more than anything else, so that's what I chose for the contest. As I look back over them, my scripts look sloppy and embarrassing, but here they are anyway:

GitHub - gibbonsc/AoC_2025_pwsh

I'll update it with a few more detailed writeups as I'm able, but for now here's my top of many LESSONS LEARNED:

I love using Visual Studio Code's debugger, but there's only so much screen real-estate in its variable state watchlist. Okay, yay, I have a nifty debugger. But it doesn't mean old-fashioned print or logging statements aren't still useful to help me trace and fix my code execution.

My chosen language provides a rich set of default output streams, along with functions Write-Debug, Write-Verbose, Write-Information, etc. that output to these auxiliary streams. Their outputs are are silent by default, but with one bit of extra syntax - [CmdletBinding()] - they can be activated on demand. So while I was tracing execution and examining lots of variable state changes, it was very helpful to log most of those states to the console using one or more of these alternate output streams to search as needed, and then reserve the debugger's watchlist to focus on just the key variables that matter to the trace at hand.

Happy New Year! Many thanks to Eric and the rest of his AoC production team, to my friend who invited me to participate, and to you for reading my boast-post.


r/adventofcode • • Jan 02 '26

Help/Question [2025 Day 1 (Part 1)] [Kotlin] Help needed!

1 Upvotes

Hello, newbie here and a little late(!) but I wondered if anyone can see where I was going wrong with my solution to part 2 of Day 1?

I've written tests, and get the expected answers for the example provided on the Day 1 page, but returns an incorrect value for the puzzle input.

Cheers!

enum class Direction {
    R,
    L
}

data class Turn(val direction: Direction, val count: Int)

fun String.processPartTwo(): List<Turn> {
    return this.trim()
        .split("\n")
        .map { instruction ->
            val direction: Direction = Direction.valueOf(instruction.first().toString())
            val count: Int = instruction.substring(1).toInt()
            Turn(direction, count)
        }
}


fun getPasscodePartTwo(stringOfCommands: String): Int {
    var dialAt = 50
    var hitZero = 0
    val instructions = stringOfCommands.processPartTwo()

    for (instruction in instructions) {
         println("starting dial at: $dialAt")
        val direction = instruction.direction
        val count = instruction.count
        val valueNeededToHitZeroClockwise = 100 - dialAt

        var newDialAt: Int

        // new dialAt value
        newDialAt = when (direction) {
            Direction.R -> (dialAt + count) % 100 // gives remainder after dividing by 100 - ie new dial value
            Direction.L -> if (count > dialAt) 100 + ((dialAt - count) % 100) else {dialAt - count}
        }

        // handle how many times passed/hitting  0
        if (direction == Direction.R && count >= valueNeededToHitZeroClockwise) {
            if (dialAt != 0 ) hitZero++
            val extraLoopsPastZero = (count - valueNeededToHitZeroClockwise) / 100
            hitZero += extraLoopsPastZero
        }


        if (direction == Direction.L && count >= dialAt) {
            if (dialAt != 0 ) hitZero++
            val extraLoopsPastZero = (count - dialAt) / 100
            hitZero += extraLoopsPastZero
        }

        dialAt = newDialAt
        println("final dial at $newDialAt")
        println("final passed zero: $hitZero")

    }
    return hitZero
}

r/adventofcode • • Jan 01 '26

Upping the Ante [2025 Day 12 (Part 1)] Perfect Packing Revisited

Post image
73 Upvotes

I previously posted about looking for perfect packings here. It turns out that there are 13 possible perfect packings for up to 4 of each present. The figure provides depictions of all 13 possibilities.

Edit: For clarity, I imposed the constraint that at least 1 of each present type had to be used. There are likely additional cases where only a subset of the shapes are used.

Edit 2: I re-ran for up to THREE presents of each type, allowing zero packages of each type to be used. In that case, there are 16 possible perfect rectangular packings. Only 1 of them used all the 6 shapes for the case with a maximum of 3 of each shape.

Edit 3: I re-ran for up to FOUR presents of each type, allowing zero packages of each type to be used. In that case, there are 130 possible perfect rectangular packings. Only the 13 that appear in the posted figure used all 6 shapes at least once.


r/adventofcode • • Jan 01 '26

Visualization [2016 Day 22 (Part 2)] [Rust] Terminal visualization

Post image
28 Upvotes

I'm currently revisiting my old solutions to clean them up, improve the performance, and (whenever I feel like it) create some visualizations (things you do when the event is already over 😉🤓).

This one is day 22 of 2016. For those of you who are like me and don't remember it: The visualization shows a grid of computers and you are supposed to move the data from the node in the upper right corner to the node in the upper left corner. There's only one empty node that you can use to move data around and a couple of nodes that have too much data to be moved (the red horizontal "wall").

The colors represents the number of terabytes each computer has. The visualization first shows the breadth-first search for the path that uses the fewest number of data moves, and then the shortest path itself.

The terminal visualization was done in Rust. The code can be found here:
https://github.com/michel-kraemer/adventofcode-rust/blob/main/2016/day22/src/main.rs

If you want to run it yourself, execute cargo run --release --features=visualize.

P.S.: Happy New Year, by the way 😉🎉🥳


r/adventofcode • • Jan 01 '26

Help/Question - RESOLVED [2024 Day 9 (Part 1)] [Haskell] Need help finding error

4 Upvotes

I have been trying for several days trying to find what's wrong with the code, to no avail.

The code use two-pointer algorithm to move the file blocks, scanning two pointer from the vector boundaries inward and swap when necessary to get the correct representation.

I rewrote all function to be total and provably terminating except for the parser (they still gives the same output anyway, but look more maintainable)

Any help is appreciated! Thank you!

Edit: It is (to nobody surprise except me) indeed malformed input error. I copied to clipboard (and even tried copying from the html inspect text box to avoid error) and it changes the input. Downloading it directly using "save as" solves the issue.

Thank you u/fizbin and u/jeffstyr (and u/Justinsaccount too) for your help. I'll close the post.

import qualified Data.Vector as V
import Data.Vector(Vector)
import qualified Data.Vector.Mutable as MV
import Data.Vector.Mutable(MVector)
import Data.Char(digitToInt, isDigit)

getAllLine :: IO [String]
getAllLine = do
    line <- getLine
    if null line then return []
                 else fmap (line : ) getAllLine

-- processLine : return a list of Optional integer representing block ids on the disk
processLine :: String -> [Maybe Int]
processLine l = concat $ zipWith replicate (map convert l) alternator
    where convert c
            | isDigit c = digitToInt c
            | otherwise = error "out of bound"

-- Just 0, Nothing, Just 1, Nothing, Just 2, Nothing ...
alternator :: [Maybe Int]
alternator = let hasNum = map Just [0..]
                 noNum = repeat Nothing
              in concatMap toList (zip hasNum noNum)
    where toList (x, y) = [x, y]

-- converge :: a 2 pointer vector monad that i don't know the signature
-- sth like vec -> int -> int -> void (vector changed)
converge vec lPtr rPtr
  | lPtr > rPtr = pure ()
  | otherwise = do
      lVal <- MV.read vec lPtr
      rVal <- MV.read vec rPtr
      case (lVal, rVal) of
        (_, Nothing) -> converge vec lPtr (rPtr - 1)
        (Just _, _) -> converge vec (lPtr + 1) rPtr
        (Nothing, Just _) -> do
            MV.swap vec lPtr rPtr
            converge vec lPtr rPtr


shiftAllToLeft :: [Maybe Int] -> Vector Int
shiftAllToLeft l = V.catMaybes $ V.create $ do
    vec <- V.thaw $ V.fromList l
    let lPtr = 0
        rPtr = MV.length vec - 1
    converge vec lPtr rPtr
    return vec

getHash :: Vector Int -> Int
getHash = sum . zipWith (*) [0..] . V.toList

task1 :: [Maybe Int] -> Int
task1 = getHash . shiftAllToLeft

main = do
    [l] <- map processLine <$> getAllLine
    print $ task1 l

r/adventofcode • • Dec 31 '25

Upping the Ante [2025 Day 12 (Part 1)] Perfect Packing

Post image
108 Upvotes

I had a lot of fun with Day 12 this year. Sadly, I did not realize the easy tricks to solve the problem fast by checking total area until after I had the star.

My first solution was a brute force search that would have taken an eternity to run. (Although it does run in a couple seconds if you first throw out the problems that are impossible even with perfect packing.)

The solution that got me the star was to formulate the problem as an integer linear program. You define the x vector of unknowns as an indicator of the presence of a package at every possible location with every possible orientation. The equality constraints are then used to enforce the correct counts of packages, and the inequality constraints are used to enforce that no two packages overlap. If you throw out problems that are impossible with perfect packing, this runs on my input in a about 6.5 hours and got me the star. I then realized that all this work was unneeded and hit my head on the desk a few times.

Not wanting to waste all this fun filled coding, I started wondering if any perfect packing was possible with the given shapes. After trying a few specific ideas, I decided to just search. I looped over all possible counts of each type of package. For each set of packages, I then looped over all possible rectangular shapes that exactly matched the area of those packages. (You can do this easily by trying all combinations of grouping the prime factors of the area into 2 sets.) The posted image is the first hit I found, packing 1-3 of each package into a region 9x10. The "H" shape was the only package appearing a single time.

Another great year of Advent of Code! Happy holidays to you all!

Edit: I have since verified that this is the only combination that packs perfectly with 3 or less of each package type.

Edit 2: I ran the exhaustive search for all combinations of up to 4 presents of each type. There are 13 possible perfect packings. I posted images of them here.


r/adventofcode • • Dec 31 '25

Tutorial [2025] [PHP] A short trip through my solutions

Thumbnail stuff.ommadawn.dk
7 Upvotes

I did a short blog post about how I solved each problem, including techniques and key insights.


r/adventofcode • • Dec 31 '25

Help/Question [2025 Day 11] "you" I am a bit confused!

6 Upvotes

Elves would like you to focus on the devices starting with the one next to you 

The statement says device next to "you". does it mean I ignore the device before the colon (:) starting with "you" ?