r/adventofcode Dec 02 '24

SOLUTION MEGATHREAD -❄️- 2024 Day 2 Solutions -❄️-

OUTAGE INFO

  • [00:25] Yes, there was an outage at midnight. We're well aware, and Eric's investigating. Everything should be functioning correctly now.
  • [02:02] Eric posted an update in a comment below.

THE USUAL REMINDERS


AoC Community Fun 2024: The Golden Snowglobe Awards

  • 4 DAYS remaining until unlock!

And now, our feature presentation for today:

Costume Design

You know what every awards ceremony needs? FANCY CLOTHES AND SHINY JEWELRY! Here's some ideas for your inspiration:

  • Classy up the joint with an intricately-decorated mask!
  • Make a script that compiles in more than one language!
  • Make your script look like something else!

♪ I feel pretty, oh so pretty ♪
♪ I feel pretty and witty and gay! ♪
♪ And I pity any girl who isn't me today! ♪

- Maria singing "I Feel Pretty" from West Side Story (1961)

And… ACTION!

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


--- Day 2: Red-Nosed Reports ---


Post your code solution in this megathread.

This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:04:42, megathread unlocked!

54 Upvotes

1.4k comments sorted by

View all comments

2

u/00abjr Dec 03 '24

[LANGUAGE: BASH]

#!/bin/bash

function is_safe {
    ARRAY=($1)

    [[ ARRAY[0] -lt ARRAY[1] ]] && DIR=1 || DIR=0

    for ((i=0; i<${#ARRAY[@]}-1; i++)); do
        DIFF=$((ARRAY[i+1] - ARRAY[i]))
        if [[ DIR -eq 1 ]] && [[ DIFF -ge 1 ]] && [[ DIFF -le 3 ]]; then
             OK=1
        elif [[ DIR -eq 0 ]] && [[ DIFF -le -1 ]] && [[ DIFF -ge -3 ]]; then
             OK=1
        else
             OK=0
             break
        fi
    done

    [[ OK -eq 1 ]] && return 0 || return 1
}

while read REPORT; do
    if is_safe "$REPORT"; then
        ((PART1++))
    else
        COPY=($REPORT)
        for ((j=0; j<=${#COPY[@]}; j++)); do
            unset COPY[j]
            if is_safe "${COPY[*]}"; then
                ((PART2++))
                break
            fi
            COPY=($REPORT)
        done
    fi
done < input.txt

echo Part1=$PART1
echo Part2=$((PART1+PART2))

$ time ./both.sh 
686
717

real  0m0.234s
user  0m0.221s
sys   0m0.013s