/r/adventofcode

Photograph via snooOG

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.

🎄 Advent of Code 🎄

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.


Rules + More Info in

our community wiki


BEFORE YOU POST
If your post is even tangentially related to a daily puzzle, use our
STANDARDIZED POST TITLE FORMAT

Solution Megathreads

December 2024

Su M T W R F Sa
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Previous years:
2023 | 2022 | 2021 | 2020 | 2019 | 2018 | 2017 | 2016 | 2015

Quick Search by Flair

Because you're lazy and we like making things easy for you. Except AoC.

Are you enjoying AoC?

Code should be fun, because otherwise it's just a job. If you'd like to support Advent of Code, please share it with all your friends, even the ones that are just learning to code! AoC is a fun, non-threatening way to work at your own pace to figure out how to apply problem-solving first, then work within a language's constraints.

If you really want to show your appreciation, donations are always appreciated. Any instances of currency will go to, in no particular order:

  • Server maintenance (hosting, bandwidth, etc.)
  • Bribes to Santa
  • Beer and sushi
  • Paper bags for /u/topaz2078 to breathe into so he doesn't hyperventilate onto another plane of (non-)existence

Support AoC

Thank you very much, and enjoy your month of code!

/r/adventofcode

123,284 Subscribers

1

[2024 Day 2 Part 2] [Python] New to python, how did I do?

So I have quite a bit of experience in C++ and C#- until I took like a 6-month break so am now rusty as hell- and decided to use this as a chance to learn python. Below is my answer for day 2, how do you think I did? Would really appreciate some data types, functions and maybe even some libraries to look into and google that would be helpful for the coming days. Also if there are any critiques or notes you can give that would be super helpful. Im hoping by the end of the month to potentially figure out some graphics library for python and make some cool visualisations so I'm hoping to figure out the basics pretty quick (again any recommendations would be super helpful).

def ParseRecords(input):
    reports = list()
    for line in input:
        numbers = list()
        currentNumber = str()

        for character in line:
            if character == " " or character == "\n":
                numbers.append(int(currentNumber))
                currentNumber = str()
                continue

            currentNumber += character
        reports.append(numbers)
    return reports

def CheckSafetyScore(report):
    score = int()
    increasing = None
    for i, level in enumerate(report):
        if i == 0:
            continue

        previousLevel = report[i - 1]
        currentLevel = report[i]

        score = currentLevel - previousLevel
        if score < -3 or score > 3 or score == 0:
            return False
        if increasing == True and score < 0:
            return False
        if increasing == False and score > 0:
            return False
        
        if score < 0:
            increasing = False
        else: increasing = True
        
    return True

reports = ParseRecords(open("Day2\input.txt"))

safeReportCount = 0
for report in reports:
    if CheckSafetyScore(report) == True:
        safeReportCount += 1 
    else: # Part 2
        for i, level in enumerate(report):
            reportCopy = report.copy()
            reportCopy.pop(i)
            if CheckSafetyScore(reportCopy) == True:
                safeReportCount += 1
                break

print(safeReportCount)

Honestly really liking the language though, I kind of had so much against it for so long because of the lack of type declarations and curly brackets but giving it a go its really quick and simple to write, even if I don't get too far in the days I'm at least glad I gave it a go.

Thanks in advance for your time!

0 Comments
2024/12/02
21:31 UTC

1

Solve Advent of Code using "CodeRun", an Online Compiler with AI Chat

Hi everyone, I have built CodeRun as hobby project. It is an online compiler with AI Chat by side. As of now it runs Python, C++, Go, Rust, JavaScript. It is live at coderun.ajaydandge.dev.

Github Repo: github.com/nobleknightt/coderun. Give it a try. If you like it, give it a star. Also, please provide your suggestions/feedback.

Thank you!

1 Comment
2024/12/02
21:22 UTC

2

[2024 Day 2 (Part 2)] [C++] Which of these unsafe sets should be safe?

This is all the unsafe sets that my code detects:

https://github.com/francescobarbieri/CodingChallenges/blob/main/AdventOfCode2024/day2/unsafe.txt

Still I get the wrong answer in day2 - part2.

In the same repository I've added some edge cases that are interpreted correctly (as far as I know) that I found on this subreddit:

https://github.com/francescobarbieri/CodingChallenges/blob/main/AdventOfCode2024/day2/edgeCases.txt

Could you please help me? I can't find the error.

Thanks, have a nice day!

5 Comments
2024/12/02
21:19 UTC

1

Instantly launch into Advent of Code Workflows using PowerToys

For those who might be interested, I wanted to share my new setup that I'll be trying out during AOCD this year.

  • I am using two new PowerToys utilties: Workspaces & New+

  • I am using the amazing Python aocd library

  • I am using PT Run to launch the workspace that I've created instantly

The end result is a really fun flow for me to get started working on AOCD every day. One launcher to:

  • Open VS Code in the directory I want within WSL in the window position I've set up
  • Open browser to AOCD site in the window position I want
  • Open File Explorer with the proper folder context
  • Open Terminal with the proper folder context
  • Create the folder scaffolding that leverages the aocd python library which makes it really simple to get started playing around with my provided input file.

You can check out a video I made about the process here if you're interested: https://youtu.be/bPKHW3_GxL4?si=taxxiMq_2C7eYg3x

0 Comments
2024/12/02
21:16 UTC

0

What is the issue today - day 02

Almost everytime the test pass, but not the input.

Which is a real pain to sift through all those 1000 lines with numbers that look the same.

Did anybody knows the issue today?

4 Comments
2024/12/02
21:10 UTC

1

Your rule set for this year?

So I've noticed that some people use special rules to complete AOC. Some people use it to learn a new language, some optimize the code for speed. Personally, I am programming this year in rust without the standard library.

How do you personally do AOC this year? Just interested in what people do :)

4 Comments
2024/12/02
21:09 UTC

2

[2024 Day -2 # (Part 1)] [C++] My answer is correct but not for my input.

my answer is >!383 !<which I think should be correct for this input>!​!<.
That's not the right answer. Curiously, it's the right answer for someone else; you might be logged in to the wrong account or just unlucky. In any case, you need to be using your puzzle input. If you're stuck, make sure you're using the full input data; there are also some general tips on the about page, or you can ask for hints on the subreddit. 

7 Comments
2024/12/02
20:36 UTC

2

[2024 Day 02 Part 2] example data works input doesn’t

I’m getting passing tests with the example data but can’t get the answer to part 1! Other than eyeballing the data (which all looks good to me) any better test data or hints from anyone?

CLARIFICATION

I wrote part 2 in the title mistakenly. I can’t get part 1 but I have no clues since my example input passes all tests.

4 Comments
2024/12/02
20:17 UTC

2

[2024 Day 1 Part 1] Question about input and help

Do we treat the input as two separate lists, or the input as two lists of lists?

Additionally, maybe I'm just dumb - but this is my general idea for solving the problem (assuming that all lists are the same length and there is always a left-right list pair):

!gather all left lists into a list, gather all right lists into a list!<

!iterate over each list side by side, finding the absolute value difference of each smallest element, 2nd smallest element, etc (can be achieved by sorting each sub list before comparing)!<

!store the difference value and continually add on until you're done with all lists - that is your answer!<

My answer keeps on coming up wrong though - the only thing I could think of is either I'm misunderstanding the problem, the inputs, or there's a slight Ruby thing that I'm missing that is messing things up

4 Comments
2024/12/02
20:17 UTC

1

[Day 02] Solution too hight

My algorithm works with the example but I cannot get the real answer right:

safe_reports = 0
counter = 0
with open('input.txt') as input:
    for report in input.readlines():
        # __import__('pdb').set_trace()
        safe = True
        asc = False
        desc = False
        report = [int(x) for x in report.strip().split(' ')]

        for i in range(len(report) - 1):
            if report[i] > report[i + 1]:
                asc = True
            else:
                desc = True

            if abs(report[i] - report[i + 1]) > 3 or (asc and desc):
                safe = False
                break

        if safe:
            safe_reports += 1

    print(safe_reports)
6 Comments
2024/12/02
20:05 UTC

2

[2024 Day 02 (part 2)][Python] I'm having trouble finding what's wrong with my answer

Hello everyone,

This is my first year participating and the challenges and the community seem very promising looking forward to participate with you all :)

def is_safe(rep):
    ptr1 = 0
    ptr2 = 1
    inc = True
    correct = True
    failed_indx = -1
    if rep[ptr1] > rep[ptr2]:
        inc = False
    if inc:
        while ptr2 != len(rep):
            diff = rep[ptr2] - rep[ptr1]
            if not 1 <= diff <= 3:
                correct = False
                failed_indx = ptr1
                break
            ptr1 += 1
            ptr2 += 1
    else:
        while ptr2 != len(rep):
            diff = rep[ptr1] - rep[ptr2] 
            if not 1 <= diff <= 3:
                correct = False
                failed_indx = ptr1
                break
            ptr1 += 1
            ptr2 += 1
    return correct, failed_indx

def count_safe_reports(reps):
    safe = 0
    for rep in reps:
        correct, failed_indx = is_safe(rep)
        if not correct:
            correct, _ = is_safe(rep[:failed_indx] + rep[failed_indx+1:])
        if correct:
            safe += 1
    return safe

I took my solution for part 1 and added a couple of modifications:

  1. Returned the index at which it initially failed
  2. Ran the function one more time with the array before and after the failed element

It worked well on the sample mini input but there was a diff of 14 elements with my input

Are there edge cases that I am not seeing? appreciate your insights

4 Comments
2024/12/02
19:30 UTC

2

Advent of code problems make me feel spoiled and skillissiues

I’m so used to always being served api data and i feels so clueless on how to use non formatted inputs like this.

Been a fun and frustrating experience so far and i feel like I’m learning again which has been a long time since I’m programming.

10 Comments
2024/12/02
19:27 UTC

3

[2024 Day 2 Part 2][Go] Help needed

I've correctly solved the first part of the problem and have coded a seemingly correct solution to the second part as well but it's not quite right. I'm having a hard time figuring out what's wrong as I've also tried out a bunch of edge cases discussed in the subreddit but they've all passed correctly. Could anyone help me with this? I'd appreciate it a lot.

package main

import (
  "bufio"
  "fmt"
  "os"
  "strings"
  "strconv"
)

func main() {
  file, err := os.Open("./day2.txt")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()

scanner := bufio.NewScanner(file)
  
  reports := make([][]int, 0)

for scanner.Scan() {
    lines := strings.Split(scanner.Text(), " ")
    report := make([]int, 0)
    for _, num := range lines {
       nInt, _ := strconv.Atoi(num)
       report = append(report, nInt)
    }
    reports = append(reports, report)
}

  safe_reports := 0
  modified_reports := 0

  for _, report := range reports {
    if isSafe(report) {
      safe_reports += 1
    } 
  }

  fmt.Printf("%d \n", safe_reports)

  // part day2

  for _, report := range reports {
    if modifySafe(report) {
      modified_reports += 1
    }  
  }
  
  fmt.Printf("%d \n", modified_reports)

if err := scanner.Err(); err != nil {
fmt.Println("Error reading file:", err)
}  
}

func absInt(num int) int {
  if num < 0 {
    return -num
  }
  return num
}

func isSafe(report []int) bool {
    status := 2 
    for i := 0; i < len(report) - 1; i++ {
      diff := report[i+1] - report[i]
      if diff == 0 || absInt(diff) > 3 {
        return false
      }
      
      if status == 2 {
        if report[i] < report[i + 1] {
          status = 0
        } else if report[i] > report[i + 1] {
          status = 1
        } else {
          return false
        } 
      } else {
        if (report[i] < report[i + 1] && status == 1) || 
        (report[i] > report[i + 1] && status == 0) {
          return false
        } 
      } 
    }
    return true
}

func modifySafe(report []int) bool {
    for i := 0; i < len(report); i++ {
        new_report := append([]int{}, report[:i]...) 
        new_report = append(new_report, report[i+1:]...) 
        if isSafe(new_report) {
          return true
        }
    }
    return false
}
4 Comments
2024/12/02
19:24 UTC

2

[2024 Day 2 Part 2] [Python] Help with Edge Case

So I've been trying to do these on and off for the last few years, and here we are again! I've been stuck here for near 3 hours now, and I'm far from the best programmer but it hurts. I've been trying to do a (rather inefficient) way of programming this, which involves running the same code that I used to complete Part 1 again, but with only the parts that failed before with the index that failed popped off (index + 1, it would be).

I've been using this test set that I found on another post, but realised that it doesn't count the first one as completable as it removes the 2. I've tried so many ways to specify edge cases that allow the 9 to be removed here, but it won't work, and I can't even get brute force to work. What obvious thing have I missed?

Update: I have now added a function where, if the program detects that there's an error in a row, it will try to run the row again with both that index and the index after it, and if either of those pass, it then adds to a second count (rows that pass in part 2 but not part 1), yet it still doesn't work, and doesn't tell me if it's too high or too low.

Test Cases:

9 2 3 4 5
1 9 3 4 5
1 2 9 4 5
1 2 3 9 5
1 2 3 4 9

The code that I currently have (not good at all, but I'd just want it to work at this point honestly) Post-Update

''' Rules:
- All levels in a row either increase or decrease
- No levels can be the same
- Increases and decreases must be between 1 and 3
'''

def probCheck(row):
    status = 0 #1 means level is increasing, -1 means level is decreasing, 0 outside of index=0 means broken
    for index, val in enumerate(row):
        if index == 0:
            if row[index] > row[index+1]: #decreasing
                status = -1
            elif row[index] < row[index+1]: #increasing
                status = 1
            else: #equal
                status = 0
                
        if (index != len(row)-1) and (status != 0): #not the last value and still okay
            if (status == -1) and not(val-1>=row[index+1]>=val-3): #if decreasing and not 1 to 3 less than former
                status = 0
            elif (status == 1) and not(val+1<=row[index+1]<=val+3): #if increasing and not 1 to 3 more than former
                status = 0   
                   
        if (status==0):
            return False
        
        if (index == len(row)-1): #last value
            return True
    

file = "day2input.txt"
levels = []

with open(file) as file:
    for line in file:
        levels.append([int(x) for x in line.split()])

safe = 0
probSafe = 0
for row in levels:
    status = 0 #1 means level is increasing, -1 means level is decreasing, 0 outside of index=0 means broken
    for index, val in enumerate(row):
        if index == 0:
            if row[index] > row[index+1]: #decreasing
                status = -1
            elif row[index] < row[index+1]: #increasing
                status = 1
            else: #equal
                status = 0
                row2 = [i for i in row]
                row2.pop(index)
                check = probCheck(row2)
                if check == True:
                    probSafe += 1
                elif check == False:
                    row2 = [i for i in row]
                    row2.pop(index+1)
                    check = probCheck(row2)
                    if check == True:
                        probSafe += 1
                    else:
                        print(row)
                
        if (index != len(row)-1) and (status != 0): #not the last value and still okay
            if (status == -1) and not(val-1>=row[index+1]>=val-3): #if decreasing and not 1 to 3 less than former
                status = 0
                row2 = [i for i in row]
                row2.pop(index)
                check = probCheck(row2)
                if check == True:
                    probSafe += 1
                elif check == False:
                    row2 = [i for i in row]
                    row2.pop(index+1)
                    check = probCheck(row2)
                    if check == True:
                        probSafe += 1
                    else:
                        print(row)
            elif (status == 1) and not(val+1<=row[index+1]<=val+3): #if increasing and not 1 to 3 more than former
                status = 0   
                row2 = [i for i in row]
                row2.pop(index)
                check = probCheck(row2)
                if check == True:
                    probSafe += 1
                elif check == False:
                    row2 = [i for i in row]
                    row2.pop(index+1)
                    check = probCheck(row2)
                    if check == True:
                        probSafe += 1
                    else:
                        print(row)
                   
        if (status==0):
            break
        
        if (index == len(row)-1): #last value
            safe += 1
    
print("Number of Safe Rows: " + str(safe)) #Answer to first part
print("Number of Safe Rows with Dampener: " + str(safe + probSafe))
6 Comments
2024/12/02
19:15 UTC

3

2024 Day 2 (Part 2) [Rust] Solution works for example but not for real input.

I honestly have no idea what I am doing wrong. Could anyone please help me?
Here is a link to the solution on Github because I wasn't sure how to format it on Reddit.

5 Comments
2024/12/02
18:37 UTC

2

Help with day 2 part 1 /2024

file = open("day2.txt", "r")
contents = file.read()
file.close()

splitted = contents.split("\n")


safe = 0

for i in splitted:
    lst = i.split(" ")
    sort = False
    nums = False

    if sorted(lst, reverse=True) == lst or sorted(lst) == lst:
        print(lst)
        sort = True
    for j in range(len(lst) -1):
        if abs(int(lst[j]) - int(lst[j+1])) in range(1,4):
            nums = True
        else:
            nums = False
            break

    if sort and nums:
        safe += 1

print(safe)file = open("day2.txt", "r")
contents = file.read()
file.close()


splitted = contents.split("\n")



safe = 0


for i in splitted:
    #lst = i.split(" ")
    lst = ['8','3','2','1']
    sort = False
    nums = False


    if sorted(lst, reverse=True) == lst or sorted(lst) == lst:
        print(lst)
        sort = True
    for j in range(len(lst) -1):
        if abs(int(lst[j]) - int(lst[j+1])) in range(1,4):
            nums = True
        else:
            nums = False
            break


    if sort and nums:
        safe += 1


print(safe)
6 Comments
2024/12/02
18:14 UTC

5

[2024 Day 2 (Part 2)] [TS] HTML Canvas animation

2 Comments
2024/12/02
18:08 UTC

2

[2024 Day 02 (both parts)][Rust] Posting my Advent of Code attempts on YouTube!

I'm not sure if self promo is allowed, but I have started recording Advent of Code for my YouTube channel - I normally only record robotics videos, but this time decided to change it up a bit!

Please take a look if you're interested in Rust and/or robotics - I'm sure my code could be improved in many ways. Watch me struggle on days 1 and 2. Feedback is very welcome!

Playlist: https://www.youtube.com/playlist?list=PLBrq1OKRHMwWVuLchtjRf0kz1GcJXsEZf

2 Comments
2024/12/02
18:05 UTC

3

[Go] Visualization libraries

This year I'm trying Go for AOC, but I'm seeing cool visualizations is making me want to do some of them. I have found some data visualization libraries lile DataViz or Glot, but I am not sure if those are going to be as flexible as I would want to do some cool, not very data focused, visualizations. Any recommendation?

1 Comment
2024/12/02
18:01 UTC

6

Need help with my solutions.. [Day 2, part 2, Rust]

So like a couple of people here I got stuck on the second part of the task for day 2. My solution works with the example input, but the submission form returns that I'm low-balling the answer it's looking for.
I've perused the subreddit for pointers or edge cases to check with my solution, but I didn't find anything I could use to narrow down my bug/misunderstanding.

Thank you in advance for any helpful pointers!

Here's my function that determines if a report is safe.

9 Comments
2024/12/02
17:57 UTC

2

Need help identifying bug - Rust, day 2 part 2

Hello everyone

I am using this AOC as an opportunity to learn Rust and I am very bad at it so far. After struggling with part 2 for a while, I have given up trying to identify the bug that my code apperently has.

I got impatient and now know that I am supposed to get 514, but get 512. And I have no idea why. From part 1 to part 2 only is_safe was changed. If at any point 2 integers are a conflict for any reason, the function will call itself recursively twice, with the array changed to have removed either one. To make sure this can only be done once, is_safe is called with a boolean indicating whether an element has been removed in the past

(I hope that makes sense, if not, please ask for clarification)

Suggestions for neat Rust tricks also welcome, as I am sure I am not using the full potential of the language.

use std::fs::File; 
use std::io::{self, BufRead};
use std::env;

fn main() -> io::Result<()> {
    let args: Vec<String> = env::args().collect();
    //println!("123 {0}", args[1]);
    let file = File::open(args[1].clone())?; 
    let reader = io::BufReader::new(file);  

    let mut cnt:i32 = 0; 
    for line in reader.lines() {


        let line = line?;
        //Takes string, makes into vector based on splitting on whitespace. Then take each element in vector and parse into integer. 
        let array1:Vec<i32> = line.split(' ').collect::<Vec<&str>>().iter().map(|s| s.parse::<i32>().unwrap()).collect();
        if is_safe (array1, false) {
            cnt = cnt + 1; 
        }
    }
    println!("cnt = {}", cnt); 
    Ok(())
}

fn is_safe(mut array1:Vec<i32>, hasremoved:bool) -> bool {
    let mut prev:i32 = array1[0];
    let mut curr:i32 = array1[1];

    let ascend:bool = prev<curr; 
    
    //if prev == curr, this will catch it regardless
    if !helper(prev, curr, ascend){
        if hasremoved {return false;}
        let mut array2 = array1.clone(); 

        array1.remove(0);
        array2.remove(1);

        return is_safe(array1, true) || is_safe(array2, true);
    }

    //Check rest of array. 
    for i in 2..(array1.len()){
        prev = curr;
        curr = array1[i]; 
        if !helper(prev, curr, ascend){
            if hasremoved {return false;}

            let mut array2 = array1.clone(); 

            array1.remove(i-1);
            array2.remove(i);

            return is_safe(array1, true) || is_safe(array2, true);

            
        }
    }

    return true; 
}

fn helper(first:i32, second:i32, ascending:bool) -> bool{
    return (((first>second) != ascending) && first != second) && ((first-second).abs() < 4)
}
7 Comments
2024/12/02
17:55 UTC

1

The code should be working!?

My code outputs all the unsafe reports as the answer it gave me is apparently too high, thus there should be false positives, but I've spent a decent time checking this output and can't find any of them!

The output on each line is the report number, followed by the report itself, followed by the differences between the levels.

amountofUnsafeReports = 0
f = open("input.txt", "r")
for line in f:
    report = line.split()
    safe = True
    diffList = []
    for i in range(1,len(report)):
        if safe == False:
            continue
        diff = int(report[i])-int(report[i-1])
        diffList.append(diff)
        if not (0 < abs(diff) < 4):
            amountofUnsafeReports+=1
            print(amountofUnsafeReports, report, diffList)
            safe = False
    if safe:
        if all(n>0 for n in diffList) or all(n<0 for n in diffList):
            continue
        else:
            amountofUnsafeReports+=1
            print(amountofUnsafeReports, report, diffList)

This is my first time coming to the reddit for help, all the other edge cases I've seen online are caught just fine by my code. I'm really stumped.

7 Comments
2024/12/02
17:27 UTC

2

[2024 Day 2 Part 2] [Python]

I am struggling with understanding what is wrong in my logic. First I am checking if it's an increasing or decreasing list by checking if the first four numbers. Then I compare two numbers and check that the new number is 1, 2 or 3 up or down from the other. Then if it is not, I compare it to the previous and nextnext(nnext) numbers to check if I should remove the one I'm "standing on" or the next one. If I have already removed something, it its index is added to count, because it is an unsafe list. I'm unsure if the total I get is too low or too high.

I tried it against a custom test case, and other test cases i found on reddit:

11 3 4 5 6 7 8 9 10
1 31 4 5 6 7 8 9 10
1 3 41 5 6 7 8 9 10
1 3 4 51 6 7 8 9 10
1 3 4 5 61 7 8 9 10
1 3 4 5 6 71 8 9 10
1 3 4 5 6 7 81 9 10
1 3 4 5 6 7 8 91 10
1 3 4 5 6 7 8 9 101
1 1 3 4 5 6 7 8 9 10
1 3 3 4 5 6 7 8 9 10
1 3 4 4 5 6 7 8 9 10
1 3 4 5 5 6 7 8 9 10
1 3 4 5 6 6 7 8 9 10
1 3 4 5 6 7 7 8 9 10
1 3 4 5 6 7 8 8 9 10
1 3 4 5 6 7 8 9 9 10
1 3 4 5 6 7 8 9 10 10
24 23 22 21 20 21 19

Here is the code:

liste=[]
b=[]

f = open('02.1.txt', 'r+')
for line in f.readlines():
    x = [int(i) for i in line.split()]
    liste.append(x)

f.close()
previous=0
next =0
count=set()


for i in range(len(liste)):
    previous=liste[i][0]
    now=liste[i][1]
    next=liste[i][2]
    nnext=liste[i][3]
    increase=None
    skipped=-1
    this=False

    if previous < now < next or previous < now < nnext or previous < next < nnext or now < next < nnext:
        increase=True
    elif previous > now > next or previous > now > nnext or previous > next > nnext or now > next > nnext:
        increase=False
    if increase == None:
        count.add(i)

    elif increase == True:
        if previous>=now or now-previous not in [1,2,3]:
            skipped=0
            if (now-previous in [1,2,3]) and (nnext-now in [1,2,3]):
                skipped=2
            if (next-previous in [1,2,3]) and (nnext-next in [1,2,3]):
                skipped=1
        for n in range(len(liste[i])-3):
            previous=liste[i][n]
            now=liste[i][n+1]
            next=liste[i][n+2]
            nnext=liste[i][n+3]
            if not(next-now in [1,2,3] or skipped == n+1):
                if skipped>=0:
                    count.add(i)
                    break
                if (now-previous in [1,2,3]) and (nnext-now in [1,2,3]):
                    skipped=n+2
                elif (next-previous in [1,2,3]) and (nnext-next in [1,2,3]):
                    skipped=n+1
                else:
                    count.add(i)
                    break
        if not liste[i][-1]-liste[i][-2] in [1,2,3] and skipped not in (len(liste[i])-2, len(liste[i])-1, -1):
            count.add(i)
    elif increase == False:
        if previous<=now or previous-now not in [1,2,3]:
            skipped=0
        for n in range(len(liste[i])-3):
            previous=liste[i][n]
            now=liste[i][n+1]
            next=liste[i][n+2]
            nnext=liste[i][n+3]
            if not(now-next in [1,2,3] or skipped == n+1):
                if skipped>=0:
                    count.add(i)
                    break
                if (previous-now in [1,2,3]) and (now-nnext in [1,2,3]):
                    skipped=n+2
                elif (previous-next in [1,2,3]) and (next-nnext in [1,2,3]):
                    skipped=n+1
                else:
                    count.add(i)
                    break
        if not liste[i][-2]-liste[i][-1] in [1,2,3] and skipped not in (len(liste[i])-2, len(liste[i])-1, -1):
            count.add(i)
print(len(liste)-len(count))
print(count)
3 Comments
2024/12/02
17:11 UTC

2

Help with my Go Solution for Day 2 Part 2

Submitted a few times now and AoC keeps saying my solution for part 2 is too low. I'm not sure what I could be doing wrong. I saw a hint to check the whole report after deleting a bad level and made sure to do that, but still getting the wrong answer. Any help would be greatly appreciated. Here's my code:

package day02
import (
    "coding-challenge-runner/pkg/input"
    "fmt"
    "os"
    "slices"
    "strconv"
    "strings"
)

func Part1(f *os.File) int64 {
    var safeCount int64 = 0
    for l := range input.Lines(f) {
       tokens := strings.Split(l, " ")
       report := make([]int, len(tokens))

       for i, s := range tokens {
          n, _ := strconv.Atoi(s)
          report[i] = n
       }

       bl := getBadLevel(report)
       if bl == nil {
          safeCount++
       }
    }

    return safeCount
}

func Part2(f *os.File) int64 {
    var safeCount int64 = 0
    j := -1
outer:
    for l := range input.Lines(f) {
       j++
       fmt.Printf("checking line %d", j)
       fmt.Println()
       tokens := strings.Split(l, " ")
       report := make([]int, len(tokens))
       damper := 1
       for i, s := range tokens {
          n, _ := strconv.Atoi(s)
          report[i] = n
       }

       for {
          if damper == -1 {
             continue outer
          }

          bl := getBadLevel(nums)
          if bl == nil {
             break
          }
          fmt.Printf("found bad level %+v", *bl)
          fmt.Println("; dampened")
          report = slices.Delete(report, bl.idx, bl.idx+1)
          damper--
       }

       safeCount++
       fmt.Println("safe")
    }

    return safeCount
}

type badLevel struct {
    val int
    idx int
}

func getBadLevel(report []int) *badLevel {
    prev := 0
    dir := false // true = asc, false = desc
    for i, n := range report {
       if i == 0 {
          prev = n
          continue
       }

       if i == 1 {
          dir = n > prev
       }

       if isBadLevel(n, prev, dir) {
          return &badLevel{
             idx: i,
             val: n,
          }
       } else {
          prev = n
       }
    }
    return nil
}

func isBadLevel(lev, prev int, dir bool) bool {
    diff := lev - prev
    if diff == 0 {
       fmt.Printf("found zero jump %d", lev)
       fmt.Println()
       return true
    }

    if dir {
       if diff > 3 {
          fmt.Printf("unsafe jump from %d to %d", prev, lev)
          fmt.Println()
          return true
       }

       if diff < 0 {
          fmt.Printf("unsafe change in dir from %d to %d", prev, lev)
          fmt.Println()
          return true
       }
    }

    if !dir {
       if diff < -3 {
          fmt.Printf("unsafe jump from %d to %d", prev, lev)
          fmt.Println()
          return true
       }

       if diff > 0 {
          fmt.Printf("unsafe change in dir from %d to %d", prev, lev)
          fmt.Println()
          return true
       }
    }

    return false
}
4 Comments
2024/12/02
17:05 UTC

3

Day 2, part 1, PHP, help

My code works for the example input.

https://onlinephp.io/c/a2af4

But with the proper input, my result is too high.

Help.

9 Comments
2024/12/02
16:35 UTC

2

[2024 day2] part2 what I am doing wrong?

For p2, I am doing a running count of bad "apples" in the levels. And if I find only one bad "apple", I consider that level as safe and add to the p1 safe total.

But I am getting wrong answer.

9 Comments
2024/12/02
16:26 UTC

Back To Top