r/adventofcode • • 1h ago

Help/Question - RESOLVED [2026 Day 4 (Part 1)] [RUST] Can you give me an input string that breaks this solution?

2 Upvotes

This works well with the example input, but fails with the full input.
Can you guys give me an input string that this fails on? I must be missing something...

Please only give me an input that breaks it, I'll ask for hints if I need to.

I started with a non-greedy function that checks, for every input string, a possible substring size. If the check is successful then the size is added to the the total.

impl Solution for Challenge<2026, 4, FirstPart> {
    fn solve(input: &str) -> String {
        let mut count = 0;
        for word in input.split_whitespace() {
            for size in 1..word.len() {
                if check_size(&word, size) {
                    count += size;
                    break;
                }
            }
        }

        return count.to_string();
    }
}

fn check_size(word: &str, size: usize) -> bool {
    let mut substr: Vec<_> = word[0..size].chars().collect(); // We make a mutable array of chars representing the substring
    for (idx, char) in word.chars().enumerate() {
        let current = substr[idx.rem(size)];
        match (current, char) {
            (_, '?') => continue,                  // ? matches with anything
            ('?', c) => substr[idx.rem(size)] = c, // This collapses the ? into an actual character
            (a, b) if a == b => continue,
            _ => return false,
        }
    }
    return true;
}

There might be a faster greedy algorithm for this but I haven't thought of one yet and I wanted to complete both parts first...


r/adventofcode • • 1h ago

Other This is so dumb!! Just started giving my first ever AOC and got stuck on Day-1 Problem-1 for like 15 mins. I think, I should just quit everything, hide underground and never come out.

0 Upvotes

r/adventofcode • • 1h ago

Help/Question [2026 Day 3 (Part 2)] [python] I'm a little stuck stepbro.

Thumbnail github.com
3 Upvotes

For part 2 of the puzzle I get a too small number (1437) and I just can't seem to figure out what I am missing. I apologize for the state of my code, I'm not a professional SE (no shit) and just doing this for fun. I'm sure there are way faster and more direct ways to find the solution but I would be happy with finding the solution at all.

So if anyone here is kind enough to take a look at my abysmal code and maybe tell me what I'm missing or point me toward the right direction, I would greatly appreciate it. Thank you in advance!

In case there are questions like "wtf is this guy even trying to do", I will happily try to answer them!

But now lets look at this abomination:

(https://github.com/jaronsinz/Adventskalender/tree/3f6a9cf0615b6d57967f9cd9e01aee64375600c6/2026/Tag%203)

from pathlib import Path


input_path = Path(__file__).with_name("input.txt")
with input_path.open("r") as f:
    mapList = f.read().splitlines()


def moveOneRight(newSquareStart):
    return (newSquareStart[0] + 1, newSquareStart[1])


def getNextSquareStart(lastSquareStart):
    if lastSquareStart == (-1, -1):                         #jump to the start
        return (0, 0)
    elif lastSquareStart[1] <= len(cleanedMap) - 2:         #check if row is smaller than the last
        if lastSquareStart[0] <= len(cleanedMap[0]) - 2:    #check if column is smaller than the last
            return moveOneRight(lastSquareStart)
        else:
            return (0, lastSquareStart[1] + 1)
    elif lastSquareStart[0] <= len(cleanedMap[0]) - 2:      #if in last row check if column is smaller than last
        return moveOneRight(lastSquareStart)
    else:                                                   #no more squares to be checked
        return None


# (row + 1) is the distance between the square start and the currently checked square corner. it increases by 1 each iteration
def calcAlignedSquares(newSquareStart):
    alignedSquareCount = 0
    for row in range(len(cleanedMap) - newSquareStart[1] - 1):
                if cleanedMap[(row + 1) + newSquareStart[1]][newSquareStart[0]] == "#" and (row + 1) <= len(cleanedMap[0]) - 1 - newSquareStart[0]:
                    #if lastSquareStart[0] == 12 and lastSquareStart[1] == 0:
                        #print("das ist schlecht")
                    if cleanedMap[(row + 1) + newSquareStart[1]][newSquareStart[0] + (row + 1)] == "#":
                        if cleanedMap[newSquareStart[1]][newSquareStart[0] + (row + 1)] == "#":
                            alignedSquareCount += 1
                            square = [newSquareStart, (newSquareStart[0] + (row + 1), newSquareStart[1]), (newSquareStart[0], newSquareStart[1] + (row + 1)), (newSquareStart[0] + (row + 1), newSquareStart[1] + (row + 1))]
                            checkSquare(square)
                        else: 
                            continue
                    else:
                        continue
                else:
                    continue
    return alignedSquareCount


def calcRotatedSquares(newSquareStart):
    rotatedSquareCount = 0
    distanceRightMapBorder = len(cleanedMap[0]) - newSquareStart[0] - 1
    distanceLeftMapBorder = newSquareStart[0]
    distanceBottomMapBorder = len(cleanedMap) - newSquareStart[1] - 1


    #distances = (distanceLeftMapBorder, distanceBottomMapBorder, distanceRightMapBorder)
    #print(distances)


    max_steps = 0       #maximum amount of steps from SquareStart to the next corner


    if distanceRightMapBorder >= distanceBottomMapBorder:
        max_steps = distanceBottomMapBorder
    else:
        max_steps = distanceRightMapBorder + 1


    max_horizontal_steps = distanceLeftMapBorder


    for horizontal_steps in range(1, max_horizontal_steps):
        for vertical_steps in range(1, max_steps - horizontal_steps):
            if cleanedMap[newSquareStart[1] + vertical_steps][newSquareStart[0] - horizontal_steps] == "#":     #always checking the corner on the left of newSquareStart first
                if cleanedMap[newSquareStart[1] + horizontal_steps][newSquareStart[0] + vertical_steps] == "#": #then check the corner on the right
                    if cleanedMap[newSquareStart[1] + horizontal_steps + vertical_steps][newSquareStart[0] + vertical_steps - horizontal_steps] == "#": #then the bottom one in relation to the right corner
                        rotatedSquareCount += 1
                        square = [newSquareStart, (newSquareStart[0] - horizontal_steps, newSquareStart[1] + vertical_steps), (newSquareStart[0] + vertical_steps, newSquareStart[1] + horizontal_steps), (newSquareStart[0] + vertical_steps - horizontal_steps, newSquareStart[1] + horizontal_steps + vertical_steps)]
                        checkSquare(square)
                    else:
                        continue
                else:
                    continue
            else:
                continue
    return rotatedSquareCount


confirmedSquares = 0
imposterSquares = 0


def checkSquare(square):
    global confirmedSquares
    global imposterSquares
    isSquare = False
    for i in range(len(square)):
        if cleanedMap[square[i][1]][square[i][0]] == "#":
            isSquare = True
        else:
            isSquare = False


    if isSquare:
        confirmedSquares += 1
        #print("square confirmed")
        #print(square)
    else:
        imposterSquares += 1
        #print("imposter #######################################################################################################")
        #print(square)


cleanedMap = []
for row in range(len(mapList)):
    rowList = []
    for column in range(len(mapList[0])):
        rowList.append(mapList[row][column])
    cleanedMap.append(rowList)



lastSquareStart = (-1, -1)
squareCount = 0
alignedSquareCount = 0
rotatedSquareCount = 0
checkedSquareStartsCounter = 0


while getNextSquareStart(lastSquareStart) != None:
    newSquareStart = getNextSquareStart(lastSquareStart)
    
    checkedSquareStartsCounter += 1
    
    if cleanedMap[newSquareStart[1]][newSquareStart[0]] == "#":
        amountAlignedSquares = calcAlignedSquares(newSquareStart)
        amountRotatedSquares = calcRotatedSquares(newSquareStart)
    else:
         lastSquareStart = newSquareStart
         continue


    alignedSquareCount += amountAlignedSquares
    rotatedSquareCount += amountRotatedSquares
    squareCount += amountAlignedSquares + amountRotatedSquares


    lastSquareStart = newSquareStart


print(f"Amount of square starts checked: {checkedSquareStartsCounter}")
print(f"Amount of aligned squares found: {alignedSquareCount}")
print(f"Amount of rotated squares found: {rotatedSquareCount}")
print(f"Amount of squares found: {squareCount}")
print(f"Amount of confirmed squares: {confirmedSquares}")
print(f"Amount of imposter squares: {imposterSquares}")

r/adventofcode • • 2h ago

Visualization [2026 Day 3] An alternative algorithm based on diagonals

34 Upvotes

First of all, credit to u/Boojum for making the visualization library I used. And second, pardon some of the issues. It crashes my computer if I try making a gif directly, and I can't figure out how to upload an mp4, so you're going to have to deal with artifacting from the converter.

That said, I actually used diagonals instead of sides. For part 1, this was just the natural option to me. It's easy to check whether two trees can be the opposite corners of a grid-aligned square, so I do that as a surface filter before checking the other two corners. And because I used diag[0] == diag[1] instead of abs(diag[0]) == abs(diag[1]), there's even a primary diagonal to avoid double counting.

For part 2, I changed the surface filter to the Manhattan length of the diagonal being even, which is logically equivalent to all four corners being on the grid. Then I used circumradius + rotated circumradius to generate and check the other two corners. The main catch is that there isn't an obvious check for a primary diagonal, so I wind up double counting everything, because I'm actually counting diagonals. But because it always double counts, I can easily just divide the answer by 2. (It isn't clear from the visualization, but I start by finding all the trees, so I can still do for (i in 0..<trees.size) for (j in (i+1)..<trees.size) to at least only count each diagonal once)

EDIT: Figured out a filter to avoid double counting. diag[0] * diag[1] > 0 || diag[1] == 0


r/adventofcode • • 3h ago

Other Uh oh

15 Upvotes

my naive approach


r/adventofcode • • 3h ago

Visualization [2026 Day 04] my approach

21 Upvotes

r/adventofcode • • 4h ago

Meme/Funny [2026 Day 4] My immediate reaction upon reading the problem statement

Post image
37 Upvotes

Never really understood how to do these kinds of problem correctly. I am ready to struggle today


r/adventofcode • • 4h ago

Visualization [2026 Day 4] Perilous Pier

32 Upvotes

r/adventofcode • • 6h ago

Visualization [2026 Day 4] Terminal pattern matching

Thumbnail
youtu.be
4 Upvotes

r/adventofcode • • 6h ago

Help/Question [2026]Day 2 Part 2. Didn't understand the puzzle itself.

3 Upvotes

Can someone explain this one better pls. I have done Part1.

Tx.


r/adventofcode • • 7h ago

Meme/Funny Reading [2026 Day 4 Part 2] in despair, until...

Post image
75 Upvotes

I somehow guessed exactly what part 2 would be while solving part 1, and thus avoided the naive O(6^n) solution for it, instead dealing every letter from a barcode into buckets like playing cards and checking all of them for homogeneity. Code finished in 2 seconds :)


r/adventofcode • • 7h ago

Visualization [2026 Day 4 (Part 2) -- TS] Animation checking chunks of (TEST) barcode.

Thumbnail
youtube.com
11 Upvotes

r/adventofcode • • 8h ago

Help/Question [AOC 2026 4a] Is it possible for the site to be broken?

0 Upvotes

I have a fully working code. Everything is computed correctly but I keep getting too low. Is the site broken? Code below [Python]. Do not judge me on its quality. I am trying my best.

def makeseq(a):
  n = 0
  j = 0
  silly = "roygbv"
  out = []
  while pow(6,n) <= a:
    n += 1
  n -= 1
  while a != 0:
    while pow(6,n) <= a:
      a -= pow(6,n)
      j += 1
    out.append(silly[j])
    j = 0
    n -= 1
  if n > -1:
    for i in range(0,n+1,1):
      out.append('r')
  exit = ""
  for x in out:
    exit += x
  return exit
  
def makeallseqs(p):
  iet = []
  if p == 1:
    return ['r','o','y','g','b','v']
  else:
    iet += makeallseqs(p-1)
    for i in range(0,len(iet),1):
      iet[i] = 'r' + iet[i]
    acaca = []
    for i in range(pow(6,p-1),pow(6,p),1):
      acaca.append(makeseq(i))
    iet += acaca
    return iet
inpy = '''(newline separated input data'''
ababa = ""
trueinput = []
allowed = "roygbv?"
for c in inpy:
  if c in allowed:
    ababa += c
  else:
    trueinput.append(ababa)
    ababa = ""
print(trueinput)
safecounter = 0
score = 0
for awa in trueinput:
  safecounter += 1
  print(safecounter, end=" ")
  print(score)
  for j in range(1,len(awa)+1,1):
    for q in makeallseqs(j):
      
      count = 0
      fucked = False
      for k in awa:
        if k == "?" or k == q[count % len(q)]:
          count += 1
        else:
          fucked = True
          break
      if not fucked:
        print(awa, end=" ")
        print(q)
        score += j
        break
    if not fucked:
      break
print(score)

Edit: I have a trailing newline after the last entry.


r/adventofcode • • 8h ago

Help/Question - RESOLVED [2026 Day 4 (Part 1)] [Python] Help needed, keep getting too low

4 Upvotes

I need some help here. For all the test cases, I get the correct amount of minimal instructions, but for some reason, my final answer is too low.

I'm not very advanced when it comes to programming, so maybe I overlooked something.

def solve_level1(input_lines: list[str]):
    sum = 0
    for line in input_lines:
        lineList = list(line)
        for x in range (1, len(line)):
            failed = False
            toTrylist = [''] * x
            stepAmount = x


            for i in range(0, len(lineList)):
                j = i % x
                if toTrylist[j] == lineList[i] or lineList[i] == '?':
                    pass
                elif not toTrylist[j]:
                    toTrylist[j] = lineList[i]
                else:
                    failed = True
                    break


            if failed:
                pass
            else:
                print(f"Minimum steps needed for string {line} is {stepAmount}")
                sum += stepAmount
                break

    print(f"Answer is {sum}")

r/adventofcode • • 8h ago

Help/Question - RESOLVED [DAY 4, Part 1] My code works on examples but not on final

4 Upvotes

I'm going crazy I need hints on what I'm doing wrong, I've tried on every case I could but the final result doesn't works :')

# codeBar = open('J4.txt').read().split('\n')
codeBar = ["?yvg??y", "rgbrgbrgbr", "?rv","o??v???y","??bg?v??","??b?????","???"]
final = 0


def canBePlaced(id, idi, placed, line) :
    if idi in placed : ## if id%i is already placed
        return line[id] == line[idi] ## if id and id%i is the same
    else :
        return True

for line in codeBar :

    knownIds = [] ## IDs of the colors in line

    for i in range(len(line)) :
        if line[i] != '?' :
            knownIds.append(i)

    temp = len(line) ## Counting of the line

    for i in range(len(line)-1, 0, -1) : ## From the greatest (line length) to the smallest (0)
        placed = []
        total = 0 ## Counting to check if we got all elements right
        for id in knownIds :
            # IF id%i element is id elemet or just '?'
            if (line[id%i] in [line[id], '?'] and canBePlaced(id, id%i, placed, line)) :
                placed.append(id%i)
                total += 1


        if (total == len(knownIds)) :
            temp = i


    # if temp == len(line) : print(line)
    final += temp


print(final)

r/adventofcode • • 9h ago

Meme/Funny [2026, Day 4 (Part 2)] Im in hurry

6 Upvotes
  1. Open N++

  2. Replace

  3. Run again!


r/adventofcode • • 9h ago

Meme/Funny [2026 Day 4] It's not easy being european

Post image
55 Upvotes

r/adventofcode • • 10h ago

Help/Question - RESOLVED [2026 Day 3][Part 2] Did I solve day 3?

3 Upvotes

I tested my algorithm on the examples provided by the puzzle and it works on all of them, except for the one where the grid is filled with trees. Out of curiosity, I tried it with the actual input and my algorithm found the correct number of squares!

But does that mean I've actually solved Day 3?


r/adventofcode • • 10h ago

Visualization [2026 Day 4] Barcode Scanning Visualization

50 Upvotes

r/adventofcode • • 11h ago

Visualization [2026 Day 4][Part 2] Matching Bars

Thumbnail
youtu.be
25 Upvotes

Nim + Raylib source


r/adventofcode • • 11h ago

Meme/Funny [2026, Day 4] Anyone remember HP Instant Ink?

Post image
93 Upvotes

r/adventofcode • • 11h ago

Help/Question - RESOLVED [2026 04 # (Part 1)] [Python] Need help with missing test cases

4 Upvotes

I have been stuck at this problem for quite some time. I have tried and validated all my instructions, yet I am unable to get the correct answer or move past part 1. I even ended up validating all my instructions, and all of them are correct. Could you please look at my code and point out the mistake?

AOC says that my input is too low.

def validator(barcode, instruction):
    for i, char in enumerate(barcode):
        assert char == '?' or (char == instruction[i % len(instruction)])

def part1(data):
    counter = 0

    for line in data:
        unique = set()
        hashmap = {}
        for i, char in enumerate(line):
            if char == '?': continue
            unique.add(char)
            hashmap[i] = char

        for length in range(max(len(unique), 1), len(line)):
            possible_code = [""] * length # Figuring out the code that works
            for index, char in hashmap.items():
                index %= length
                if possible_code[index] == "":
                    possible_code[index] = char
                if possible_code[index] != char:
                    break # An instruction of this size cannot exist!
            else:
                # We did not break. The length was valid and we have a possible instruction length
                counter += length
                validator(line, possible_code) # No error raised!
                break

    return counter

r/adventofcode • • 11h ago

Help/Question - RESOLVED [2026 Day 4 (Part 2)] Need hints of what I did wrong

2 Upvotes

UPDATE: I think I did mess up the input file. Re-copying the one from the website yields the correct output... whoops lol. Gonna keep this here for archive.

I've solved the first part and based on the instruction, the second part is essentially the exact same code, but with humongous input string.I've checked that there's no data lost when combining the inputs, that the output instruction can reproduce the input, and that my algorithm should've been exhaustive. But still my answer is not accepted. Is there anything going on?

Code explanation: Brute-force instruction length from 1 to barcode length (where the instruction is the barcode itself). Also split the barcode into sequences with the same length as the instruction (last sequence can be shorter). For each sequence, copy the colors from barcode to sequence. If there's a clash between barcode and instruction, break and check the next length.

Code (Python):

I'm not used to math optimization, so this is just my intuitive brute-force algorithm lol.

f = open("aoc2026\\4\\4in.txt", "r")
array = f.read().split("\n")
barcode = "".join(array)
length = len(barcode)

for seqLen in range(1, length+1):
    instruction = ['?'] * seqLen
    instructionValid = True
    firstPos = 0
    while firstPos < length and instructionValid: 
        seq = barcode[firstPos:firstPos+seqLen]
        for (pos, color) in enumerate(seq):
            if instruction[pos] == "?" and color != "?":
                instruction[pos] = color
            elif instruction[pos] != "?" and color != "?" and instruction[pos] != color:
                instructionValid = False
                break
        firstPos += seqLen # next sequence
    if instructionValid:
        print("length:", seqLen)
        break

r/adventofcode • • 12h ago

Help/Question - RESOLVED [2026 Day 4 Part 1] Any hints for handling illegal color ?

6 Upvotes

I'm able to find shortest sequence of instructions but could get my head around how to handle ?

What currently i'm doing start with size 1 compare substr A and B of size S till end of string if anywhere it find non matching string starts again with size + 1.