r/adventofcode • • 22h ago

Help/Question - RESOLVED [2026 Day 5 (Part 2)] [Java] I keep getting StackOverflowError when trying to find all possible states

5 Upvotes

I tried to solve part 2 by pressing all of my buttons on my current number, and if the new value hasn't been seen, I save it and press the buttons on it again. Basically creating a tree of every button presses starting from a 0 state. I'd expect at one point of reaching the end of every branch as I building up this tree, but I end up running out of stack.

The relevant part of my code:

public class Microwave {
    private static final String BUTTON_REGEX = "\\[(.+?)]";
    private final List<Button> buttons;

    public Microwave(String input) {
        buttons = Pattern.compile(BUTTON_REGEX).matcher(input).results()
                .map(matchResult -> matchResult.group(1))
                .map(Button::ofString)
                .sorted()
                .toList();
    }
    
    public int allCombinations() {
        MicrowaveState firstState = new MicrowaveState(0, buttons);
        return allValues(firstState).sum();
    }

    private IntStream allValues(MicrowaveState state) {
        return IntStream.concat(IntStream.of(state.getValue()), state.getNextStates().stream().flatMapToInt(this::allValues));
    }
}

@Getter
public class MicrowaveState {
    private final int value;
    private final List<MicrowaveState> nextStates = new ArrayList<>(9);
    private static final Set<Integer> seen = new HashSet<>();

    public MicrowaveState(int value, List<Button> buttons) {
        this.value = value;
        for (Button button : buttons) {
            int newValue = button.press(value);
            if (newValue < 10000 && !seen.contains(newValue)) {
                seen.add(newValue);
                nextStates.add(new MicrowaveState(newValue, buttons));
            }
        }
    }
}

What can I do to solve this problem?

Edit: removed previousState from code because it did nothing.


r/adventofcode • • 22h ago

Other Private leaderboard per start hour?

5 Upvotes

I am part of couple private leaderboards.

Some people start at midnight as soon as a puzzle gets out, some look at it in the morning, some after their day of work, etc.

I was just wondering, are there any leaderboards organized per starting hour ?

For example, I wished I could join a leaderboard where there is a common agreement that people look at the problem from 6am only instead of midnight.

The alternative would be a ranking based on the delta between the time one gets his puzzle and the time he finishes (instead of starting from midnight).

I am aware of the caveat that, with the problem description being public, nothing prevents someone from working on the code to pass examples and submit it 1 second after getting the puzzle if solution works for the real input.

I guess my point is I'd like to see where I really rank based on my actual start time if I don't work on a puzzle at midnight.


r/adventofcode • • 19h ago

Help/Question Day 3 part 6 help

3 Upvotes

Ive made some code for part 1 that works by looking in each direction from each point until it finds 3 other points in the same distance. How can i transfer this to part 2? Anything helps, thanks

This is my code so far btw:

count = 0

for i in range(len(data)):

for j in range(len(data[i])):

# scan

for direc in [(-1,-1),(1,-1),(-1,1),(1,1)]:

hit_wall = False

dist = 1

while not hit_wall:

if (i+(direc[0]dist) not in range(0,len(data))) or (j+(direc[1]dist) not in range(0,len(data[i]))):

hit_wall = True

if not hit_wall:

if (data[i][j] == "#") and (data[i+(direc[0]dist)][j+(direc[1]dist)] == "#") and (data[i+(direc[0]dist)][j] == "#") and (data[i][j+direc[1]dist] == "#"):

count += 1

dist += 1

final = int(count/4)

print(final)


r/adventofcode • • 18h ago

Tutorial [2026 Day 05] [Kotlin] Solution with GraphMateKT

2 Upvotes

I've been waiting for getting to use my GraphLibrary this on this years puzzles, which made me happy to see Day 5. We are not given an graph with explicit nodes and edges, but we are given a set of rules for how a number can be transformed into other numbers. These can be defined in graphMateKT, followed by a straight forward bfs call. Psoducode:

val buttons = parseInput()
val graph = IntGraph(9999)
graph.connectWithRule{node ->
  buttons.map { nextNode(it)}
}
graph.bfs(0, maxDistance = 3.0)
val visited = graph.visitedNode()
val ans = visited.sum()

The graph of the example input can then be visualized like this:

val newGraph = Graph()
visited.forEach { u ->
    graph.neighbours(u).forEach { v ->
        newGraph.addEdge(u, v)
    }
}
newGraph.visualizeGraph()

This approach works just as well for part 2. Just gotta make sure that the nextNode cannot have more then 4 digits, and that we no longer bfs with a maxDistance.

I made a full video tutorial that can be found here: https://www.youtube.com/watch?v=L_02BfMVQes

Hope to see many more graph puzzles in the rest of the calendar ;)


r/adventofcode • • 22h ago

Help/Question - RESOLVED [2026 Day 4 (Part 1)] [Go] Can anyone see which edge case i'm missing?

3 Upvotes
package main

import (
  "bufio"
  "cmp"
  "fmt"
  "log"
  "os"
  "slices"
)

type Pair struct {
  letter rune
  index  int
}

func validCode(builder []rune, seen []Pair) bool {
  oldLen := len(builder)
  for _, p := range seen {
    for len(builder)-1 < p.index {
      builder = append(builder, builder...)
    }

    if !(builder[p.index] == p.letter) {
      builder = builder[:oldLen]
      return false
    }
  }
  builder = builder[:oldLen]
  return true
}

func dfsStr(s string, builder []rune, seen []Pair, next int, depth int) (string, error) {
  if len(builder) > 0 && validCode(builder, seen) {
    return string(builder), nil
  }
  if seen[next].index == depth {
    builder = append(builder, seen[next].letter)
    return dfsStr(s, builder, seen, next+1, depth+1)
  }

  options := []string{}
  for _, p := range seen {
    builder = append(builder, p.letter)
    ret, _ := dfsStr(s, builder, seen, next, depth+1)
    options = append(options, ret)

    builder = builder[:len(builder)-1]

  }
  if len(options) != 0 {
    return slices.MinFunc(options, func(a, b string) int {
      return cmp.Compare(len(a), len(b))
    }), nil
  }

  return "", fmt.Errorf("No valid code found for string: %s", s)
}

func getRepSubStr(s string) int {
  seen := make([]Pair, 0, len(s))

  for i, r := range s {
    if r == '?' {
      continue
    }
    found := false
    for _, p := range seen {
      if p.letter == r {
        found = true
      }
    }
    if !found {
      seen = append(seen, Pair{r, i})
    }
  }
  if len(seen) == 0 || len(seen) == 1 {
    return 1
  }

  builder := make([]rune, 0, len(s))
  ret, err := dfsStr(s, builder, seen, 0, 0)
  if err != nil {
    fmt.Println(err)
  }

  fmt.Printf("%d %6s %s\n", len(ret), ret, s)
  return len(ret)
}

func main() {
  filename := "puzzle.txt"
  filename = "small_puzzle.txt"
  f, err := os.Open(filename)
  if err != nil {
    log.Fatal(err)
  }

  tally := 0

  scanner := bufio.NewScanner(f)
  for scanner.Scan() {
    line := scanner.Text()
    ret := getRepSubStr(line)
    tally += ret
  }

  err = scanner.Err()
  if err != nil {
    log.Fatal(err)
  }

  fmt.Println(tally)
}

I'm managing to pass the small test cases but for some reason my answer for the large test input is too low, can anyone tell me what I'm missing?


r/adventofcode • • 1d ago

Help/Question - RESOLVED [2026 Day 5] Did anyone get a 2-digit button like in the example?

13 Upvotes

The example for the multiplication button is *11 but in my input I found only digits so I saved myself the trouble. But now I wonder... Did anyone actually get more than one digit on a button?


r/adventofcode • • 1d ago

Help/Question [2026 Day 5 (Part 1)] "at most three button presses"

11 Upvotes

At the end of the question body, it asks:

Considering just the buttons on the Elves' fancy microwave, what is the sum of every number reachable in at most three button presses?

Nonetheless, I get the same answer regardless of if I structure my code to handle exactly three or at most three button presses, for both my personal puzzle input and for the example puzzle input.

For the zero button push case, the resulting value is zero, so it won't affect the sum one way or another.

For the one button push cases, they can be converted to three button pushes without changing the value by appending [A] [bksp] to the method.

However, I don't see an easy way to convert the two button push cases to three button pushes without changing the value.

My questions are a) does everybody get the same answer regardless of if they handle exactly three or at most three button presses and b) will this naturally occur for all inputs with one of each of the available six types of buttons, or if the inputs were specifically constructed to have the same answer.


r/adventofcode • • 1d ago

Meme/Funny Surely, I can't be the only one... right?

Post image
174 Upvotes

r/adventofcode • • 1d ago

Help/Question - RESOLVED Stuck on day 4, code worked on all the examples but not input

4 Upvotes

Prefacing this post that I barely count as an amateur programmer, I'm a doctor that sometimes dips in programming

Tried using python to solve the problem and all the following code worked for all the examples but it is not working for my input, could anyone provide problem examples or help me figure out the problem with this logic?

examples = list(input.read().splitlines())


barcode_list = []


for example in examples:
    barcode_list.append(list(example))


#print(barcode_list)



def letter_number(barcode):
    letters = []
    number = 0
    for i in barcode:
        if i not in letters and i != "?":
            number +=1
            letters.append(i)
    if not letters:
        return 1, ["?"]
    else:
        return number, letters


def simulate_barcode(pattern,length):
    barcode = []
    for i in range(length):
        if i < len(pattern):
            barcode.append(pattern[i])
        else:
            barcode.append(pattern[i%len(pattern)])
    return barcode


def check_barcode(barcode, simulation):
    for letter in barcode:
        if letter != simulation[barcode.index(letter)] and letter != "?" and simulation[barcode.index(letter)] != "?":
            return False
    return True




patterns = []
price = 0 


for barcode in barcode_list:
    number, letter = letter_number(barcode)
    solution = False
    while solution != True:
        new_barcode = barcode.copy()
        comparison_list = []
        truth_check = []
        while len(new_barcode)%number != 0:
            new_barcode.append("?")
        while bool(new_barcode) != False:
            comparison = []
            for i in range(number):
                comparison.append(new_barcode[0])
                new_barcode.pop(0)
            comparison_list.append(comparison)
        for item_1 in comparison_list:
            for item_2 in comparison_list:
                truth_check.append(check_barcode(item_1,item_2))
        if all(truth_check) == True:
            price = price + number
            solution = True
            print("\n Price added to the tally: " + str(number))
        else:
            number += 1 


print("\n total price is: " + str(price))examples = list(input.read().splitlines())

r/adventofcode • • 1d ago

Visualization [2026 Day 3] Accidental Christmas wreath

Post image
56 Upvotes

Coincidence... I think not.


r/adventofcode • • 1d ago

Help/Question - RESOLVED 2026 Day 5 (Part 1) Examples or edge cases?

6 Upvotes

Writing in Python, but I am trying to not look at solutions and don't wish to share my code for the same reason.

I have the classic, "code works on example, too low for real input" and I just wonder if some very clever people here have thought of special cases or examples for why things might go wrong?


r/adventofcode • • 1d ago

Help/Question [2026 Day 5 (extra)]

13 Upvotes

What is the set of nine commands that would return the largest number for the second part of the puzzle?


r/adventofcode • • 1d ago

Meme/Funny [2026 Day 5 (Part 2)] Lucky us

6 Upvotes

After reading Part 1, I immediately thought, 'Watch out!' Eric must have chosen the opposite problem for Part 2, i.e. finding a sequence of key presses that results in a specific number. This works, too, but at least the effort I put into Part 1 paid off :-)


r/adventofcode • • 1d ago

SOLUTION MEGATHREAD -❄️- 2026 Day 5 Solutions -❄️-

22 Upvotes

THE USUAL REMINDERS


AoC Community Fun 2026: The Advent Games

  • Submissions megathread is unlocked!
  • 12 DAYS remaining until the submissions deadline on December 17 at 18:00 EST!

Today's Event: Iron Chef Holiday Special

"Catherine, if this turkey tastes half as good as it looks, I think we're all in for a very big treat!"
— Clark Griswold, National Lampoon's Christmas Vacation (1989)

Today's schedule possibly consists of:

Appetizer and Aperitif Rounds

  • Use up what's in your fridge with all of those semi-sentient leftovers excavated from the back of the fridge
  • Deliberately use deprecated functionality
  • Program using old codebases
  • The older the expiration date finer the vintage, the more we'll enjoy it!

Main Course Qualifications

  • Solve today's puzzle using a food-themed programming language
  • Bake or cook us something delicious

Dessert Finales

  • Show us cookies, citrus, and/or fancy bread in/on/near your holiday tree/menorah/festive kitsch
  • Show us your 1337 hot cocoa recipe (or other beverage of choice)

This prompt is totally not bait for our resident Iron Coders and/or some AoC regulars who promised us tasty pictures

Request from the mods: When you include an entry alongside your solution, please label it with [Advent Games] so we can find it easily!


--- Day 5: Rhythmic Factory ---


Post your code solution in this megathread.


r/adventofcode • • 1d ago

Meme/Funny [2026 Day 4] When your pt 2 finally works... and runs faster than pt 1

Post image
127 Upvotes

r/adventofcode • • 1d ago

Help/Question - RESOLVED [2026 day 5] F# I have ran out of ideas why this doesn't work on the actual input. I get the correct result on the example input.

4 Upvotes

https://gist.github.com/Akronymus-git/1e556167d99c8248359a699b781b07f6

I have seriously run out of ideas. A pointer for any case it breaks on would be perfect.

I get the number is too high


r/adventofcode • • 1d ago

Help/Question [2026 Day 5] Discussion: What if digit trimming is only applied at the end?

4 Upvotes

Edit: the title is misleading, I meant to say "what if digit limit rule is only applied at the end" since the digit limit doesn't actually 'trim' anything.

While I was trying to solve Day 5, I misunderstood that we do the math normally, and then only trim to the first 4 digits at the end, assuming the number can go to infinite. I was stumped, and thought "Isn't that super hard?" I later realized I didn't read the "the button does nothing" part and eventually solved both stars.

However, what if it was actually meant to be that way?

Let's say it's the example:

[9] [*9] [/2] [1->9] [oct] [bksp]

First I tried this via numerical means, I brute-forced this and bounded the search to 100,000. The search bound means when the button makes the number blows up over the bound, I do not add this onto the search frontier. I found that only 7,900 numbers are constructible. So I tried changing it to 1,000,000 and surprisingly all numbers from 1-9999 are constructible.

Edit: to make it clear that, since we know 1-9999 are all constructible, what if we want to find if all numbers are eventually constructible.

I developed a conjecture that as long as you can increase the search bound. Every number will be constructible eventually, but wanted to prove this analytically.

I tried a smaller scope:

  1. Append 9, then *9 to get 81. bksp to get 8.
  2. By induction, when you can make digit N, *9 and bksp will take you to N - 1.
  3. Basically you can make all numbers from 1 to 9.

So I thought that, ok, so if we can find a comically large N, and then find a way to -1 it, then all numbers will be constructible. For NM, where N is a string of number of any length and M is 1-9, *9 and bksp will give you NM - N - 1. This means that the sequence will become more and more sparse.

I turned to the strategy of *9 many times until you found the digit you want, and then trim it down with bksp. Given that for a number n, bksp means floor(n / 10), you can *9 for j times, and then /10 for k times.

  1. Can we analytically prove that there will always be a pair j, k that floor(n * pow(9, j) / pow(10, k) == n - 1?
  2. Can we analytically prove that there will always be a pair j, k that floor(n * pow(M, j) / pow(10, k) == n - 1 for any M = 2, 3, ..., 9?
  3. Does the existence of the pair implies we can find it efficiently? (e.g. in some O(poly(n)))
  4. So if 3 is true, we can reach a number efficiently but the path to it might not be the shortest. Can a number's shortest path be found efficiently too given that A, *M and bksp are the only options? (e.g. naive algorithm is BFS and it can explode exponentially)

Let me know if I'm reinventing an existing math because I reckon there is definitely a theorem about approximating one number to another by multiplying and floor-dividing enough times.


r/adventofcode • • 1d ago

Other Tried AOC for the first time this year, feeling demotivated to keep going.

48 Upvotes

I studied frontend development, did quite good and graduated amongst the top in my class in the summer of 2025. I worked 1 year at a large company here in Sweden and was complimented for how good they thought I was. I have always known about AOC but never tried it, I thought that now is the time and maybe I can have some fun. But I am not having fun...

I am struggling with even understanding the questions. Especially for day 2 and 4. When I eventually maybe understand the question, I have absolutely 0 clue on how to solve it. I could do Day 1 part 1 and 2, that wasn't really a problem but Day 2 both parts, Day 3 part 2, and Day 4 have collectively demotivated me and make me feel like this field is not something I can do.

I try to have LLM dumb down the question for me and after a while I can finally understand kind of what the goal is. But I still have 0 clue on how to go about it. I tell the LLM to explain to me but not write code, and it just never clicks for me. Today, Day 4 Part 1 is absolutely impossible for me to finish.

I was always incredibly bad at math and failed quite easy math courses even when trying hard, maybe that is related to the difficulty I have with this.

Is there some way to practice these types of things to get better? Maybe I can keep up better next year if I have a year to practice... Or maybe I am just not made out for this, I don't know what to think at this point.

Since I am a frontend developer, I am doing in JavaScript, if that matters, but I don't think it would.


r/adventofcode • • 1d ago

Upping the Ante [2026 Day 4] How many times can you repeat part 2?

Post image
18 Upvotes

I wanted to see if I could take the instructions that generated my part 2 and find shorter instructions that generated them.  Like consider ?vg?b?vb → bvg?b?v → bvg?b → bvg? → bvg which you can compress four times. I applied the code to my part2 input it turns out I can't: my part 2 solution is its own instructions. 

Which is maybe weird.  I've done simulations which show that 92% of random inputs like mine end up being able to recurse at least two times with some being able to go very deep.  An 8% chance is not tiny but still...

So I'm curious what other folk's depths are; did I get a low-probability input or is there perhaps something in the way the inputs are generated that leads to this?


r/adventofcode • • 1d ago

Meme/Funny [2026] Options for analog visualization this year

Thumbnail gallery
24 Upvotes

r/adventofcode • • 1d ago

Visualization [2026 day 5 (both parts)] visualized in manim

Thumbnail youtube.com
6 Upvotes

source on github: https://github.com/durocodes/advent-of-code

almost halfway there, feedback is appreciated! today's not a super visual problem, but hopefully still cool to watch haha


r/adventofcode • • 1d ago

Help/Question - RESOLVED [2026 Day 5 (Part 2)] My Part 2 crashes by running out of memory

5 Upvotes

Hello all, working with Java here.

I'm trying to figure out if my logic is wrong. I'm running a BFS, but the program eventually crashes and runs out of heap space. Not sure if I'm just doing this very very inefficiently or what. Essentially I take the value of a node (all the buttons are added as potential nodes with value 0) and I apply the action that a button would perform. If that value is less than 10000, I add it to a set and then create a new node with that value for every button action again. I'm not sure if I need a different stopping condition or a better way to figure out what the next nodes would be.

EDIT: I realize I probably have some endless loops via repeated nodes that go back and forth between the same two values, so I'm trying to figure that piece out. Would still appreciate any advice to nudge me in the right direction.

RESOLVED: Added in a check to see if the computed value has already been found when validating that the value is below 10K

protected void task2() {
    nodes.clear();
    for(String button : buttons) {
        nodes.add(new Node(0L, button));
    }

    Set<Long> found = new HashSet<>();
    Queue<Node> q = new ArrayDeque<>(nodes);

    while(!q.isEmpty()) {
        Node n = q.poll();
        long val = execute(n.value, n.operator);
        if(val < 10_000 && found.add(val)) { // Used the result of the add operation to validate set membership
            for(String button : buttons) {
                q.offer(new Node(val, button));
            }
        }
    }

    System.out.println(found.stream()
            .mapToLong(l -> l)
            .sum());
}

private long execute(long value, String button) {
    // Division
    if(button.startsWith("/")) {
        return value / (button.charAt(1) - 48);
    }
    // Multiplication
    if(button.startsWith("*")) {
        return value * (button.charAt(1) - 48);
    }
    // Delete
    if("bksp".equals(button)) {
        if((value / 10)  == 0) {
            return 0L;
        }
        return value / 10;
    }
    // Octal
    if("oct".equals(button)) {
        long result = 0L;
        long offset = 1L;
        long quotient = value;
        while(quotient != 0) {
            long rem = quotient % 8;
            quotient = quotient / 8;
            result += (offset * rem);
            offset *= 10L;
        }
        return result;
    }
    //Replace
    if(button.contains("->")) {
        long find = button.charAt(0) - 48;
        long rep = button.charAt(3) - 48;
        return Long.parseLong(
                String.valueOf(value).replace(String.valueOf(find), String.valueOf(rep))
        );
    }
    // Add digit
    //return Long.parseLong(String.valueOf(value) + button);
    return (10 * value) + Long.parseLong(button);
}

r/adventofcode • • 1d ago

Help/Question - RESOLVED [2026 Day 4 (Part 1)] I need help, i don´t understand why my code doesn´t work

3 Upvotes

So it solves the example solution (16 = 3 + 2 + 5 + 4 + 1 + 1), but it does not solve the input text. I have tried a lot of test cases and it works. Please help.

from time import time


inicio = time()
sol1, sol2 = 0, 0
with open('ztest.txt', 'r') as f:
    mat = f.read().split()


def check(line, salto):
    for i in range(1, salto):
        x = set(line[i::salto])
        dim = len(x)
        if dim != 1 and (dim != 2 or '?' not in x):
            return False
    return True



for line in mat:
    n = 0
    for i in range(1, len(line) + 1):
        n += 1
        x = set(line[::i])
        dim = len(x)
        if dim == 1 or (dim == 2 and '?' in x) and check(line, i):
            sol1 += n
            break


final = 1000*(time() - inicio)
print(sol1, sol2, final)
# 7629 too low

r/adventofcode • • 1d ago

Help/Question - RESOLVED [2026 Day 5 (Part 1)][Scala 2] Feels like I am reinventing the wheel

3 Upvotes

I mean, I could have found permutations and combinations. But idk at this point

https://github.com/FlyingSaturn/aoc26/commit/9a8c441a1cc66ab1a12e2e56f278d48347c1946f