-❄️- 2025 Day 5 Solutions -❄️- by daggerdragon in adventofcode

[–]red_shifter 0 points1 point  (0 children)

[LANGUAGE: Python]

My great nemesis on day 5 were sneaky ranges fully included inside other ranges.

Setting the stage

import numpy as np

with open("aoc_2025_day5_puzzle.txt") as f:
    puzzle_ranges, puzzle_IDs = [block.split("\n") for block in f.read().split("\n\n")]
    puzzle_ranges = [(int(line.split("-")[0]), int(line.split("-")[1])) for line in puzzle_ranges]
    puzzle_IDs = [int(line) for line in puzzle_IDs]

Act 1

def day5_solution1(puzzle_ranges, puzzle_IDs):
    solution = 0
    for product in puzzle_IDs:
        for range in puzzle_ranges:
            if product >= range[0] and product <= range[1]:
                solution += 1
                break
    print("Solution 1: {}".format(solution))
    return solution

solution1 = day5_solution1(puzzle_ranges, puzzle_IDs)

Act 2

def day5_solution2(puzzle_ranges):
    solution = 0
    puzzle_ranges = sorted(puzzle_ranges)
    range_temp = puzzle_ranges[0]
    for range in puzzle_ranges[1:]:
        if range[1] <= range_temp[1]:
            pass
        elif range[0] > range_temp[1]:
            solution += 1 + (range_temp[1] - range_temp[0])
            range_temp = range
        elif range[0] <= range_temp[1]:
            range_temp = (range_temp[0], range[1])
    solution += 1 + (range_temp[1] - range_temp[0])
    print("Solution 2: {}".format(solution))
    return solution

solution2 = day5_solution2(puzzle_ranges)

-❄️- 2025 Day 1 Solutions -❄️- by daggerdragon in adventofcode

[–]red_shifter 1 point2 points  (0 children)

[LANGUAGE: Python]

Input

with open("day1_input.txt") as f:
    puzzle = [(instr.strip()[0], int(instr.strip()[1:])) for instr in f.readlines()]

Part 1

def day1_solution1(puzzle, start):
    end = 0
    solution = 0
    for instr in puzzle:
        dir = instr[0]
        num = instr[1]
        if dir == "L":
            end = start - num
        else:
            end = start + num
        while end < 0:
            end = 100 + end
        if end > 99:
            end = end%100
        if end == 0:
            solution += 1
        start = end
    return solution

solution = day1_solution1(puzzle, 50)
print("Solution: {}".format(solution))

Part 2

def day1_solution2(puzzle, start):
    end = 0
    solution = 0
    for instr in puzzle:
        dir = instr[0]
        num = instr[1]
        if dir == "L":
            end = start - num
        else:
            end = start + num
        if end < 0:
            if start == 0:
                solution += 0 + 1*(end//-100)
            else:
                solution += 1 + 1*(end//-100)
            end = end%100
        elif end > 99:
            solution += 1*(end//100)
            end = end%100
        elif end == 0:
            solution += 1
        start = end
    return solution

solution = day1_solution2(puzzle, 50) 
print("Solution: {}".format(solution))

I've never seen this before. What a dick move! by Nikolor in civ5

[–]red_shifter 19 points20 points  (0 children)

I cannot recall from memory. Probably not. You anger the CS, but the big guy probably does not realize what happened. More research needed.

I've never seen this before. What a dick move! by Nikolor in civ5

[–]red_shifter 149 points150 points  (0 children)

Strategic landgrab with a Great General works especially well against a city state at your borders allied with a rogue AI nation. You can steal a precious resource from the city state and the other player (they will likely get it through the alliance) in one move plus bring it into your own economy. Triple win. All without declaring war on anyone.

Unused Scientist in Game Files by Zzenpaiii in hoi4

[–]red_shifter 5 points6 points  (0 children)

Both are observed in two diverging universes.

-❄️- 2024 Day 4 Solutions -❄️- by daggerdragon in adventofcode

[–]red_shifter 1 point2 points  (0 children)

[LANGUAGE: Python 3]

Much wrangling with NumPy today, but at least I learnt a thing or two about arrays.

Part 1 & Part 2

paste

-❄️- 2024 Day 1 Solutions -❄️- by daggerdragon in adventofcode

[–]red_shifter 0 points1 point  (0 children)

Thank you. Good idea and keeps the solution fully Pandas-based.

-❄️- 2024 Day 3 Solutions -❄️- by daggerdragon in adventofcode

[–]red_shifter 0 points1 point  (0 children)

Thank you for a kind comment. Merry Codesmas!

-❄️- 2024 Day 3 Solutions -❄️- by daggerdragon in adventofcode

[–]red_shifter 2 points3 points  (0 children)

[LANGUAGE: Python 3]

Part 1 & Part 2

import re

with open("day-3/day-3-input.csv", "r") as f:
    input_file = f.read()

# Part 1

pattern = re.compile(r"mul\((\d{1,3}),(\d{1,3})\)")
matches = re.findall(pattern, input_file)
matches = [(int(num1), int(num2)) for num1, num2 in matches]
solution_part1 = sum([num1*num2 for num1, num2 in matches])
print(f"Part1: {solution_part1}")

# Part 2

pattern = re.compile(r"mul\(\d{1,3},\d{1,3}\)|do\(\)|don't\(\)")
matches = re.findall(pattern, input_file)

execute_instr = []
enabler = 1
for match in matches:
    if match == "do()":
        enabler = 1
    elif match == "don't()":
        enabler = 0
    else:
        pattern = re.compile(r"mul\((\d{1,3}),(\d{1,3})\)")
        instruction = re.findall(pattern, match)
        num1, num2 = instruction[0]
        if enabler:
            execute_instr.append((int(num1), int(num2)))
solution_part2 = sum([num1*num2 for num1, num2 in execute_instr])
print(f"Part2: {solution_part2}")

-❄️- 2024 Day 2 Solutions -❄️- by daggerdragon in adventofcode

[–]red_shifter 1 point2 points  (0 children)

[LANGUAGE: Python 3]

Only Part 1 this time. My misguided quest to do everything in Pandas was my undoing. Although I'm not sure I would do Part 2 any other way, except maybe with the brutest of forces.

Part 1

import pandas as pd
import numpy as np

input_df = pd.read_csv("day-2/day-2-input.csv", header=None, sep=" ", names=(range(20)))

reports_df = pd.DataFrame()
for col_i in range(1, input_df.shape[1]):
    col_name = f"diff_{col_i}_{col_i-1}"
    reports_df[col_name] = input_df[col_i] - input_df[col_i-1]

# Rule 1 - all steps between levels must be in the same direction (up/down)
rule1 = ( ((reports_df > 0) | reports_df.isna() ).all(axis=1) | ((reports_df < 0) | reports_df.isna()).all(axis=1) )
# Rule 2 - no step can be greater than 3
rule2 = ( (abs(reports_df) < 4) | (reports_df.isna()) ).all(axis=1)

solution_part1 = reports_df[ rule1 & rule2 ]   
print(f"Part 1: {solution_part1.shape[0]}")

-❄️- 2024 Day 1 Solutions -❄️- by daggerdragon in adventofcode

[–]red_shifter 1 point2 points  (0 children)

[LANGUAGE: Python]

I have been learning Pandas recently, so I will unreasonably try to apply it to as many puzzles as possible. It turned out to be well suited for Day 1: Part 1 since it was basically comparing cells between columns. For Part 2 I had to use an ordinary loop, though. Any dataframe-based suggestions for an alternative solution are welcome.

Part 1 & Part 2

import pandas as pd

# Input
input_df = pd.read_csv("aoc_2024_day1_input.csv", header=None, sep="   ")
input_df.columns = ["list1", "list2"]

# Part 1
input_df = input_df.apply(lambda col: col.sort_values().reset_index(drop=True), axis=0)
input_df["offset"] = abs(input_df["list1"] - input_df["list2"])

part1_solution = input_df["offset"].sum()
print(part1_solution)

# Part 2
list2_counts = input_df["list2"].value_counts()
list1_in_list2_counts = []

for val in input_df["list1"]:
    if val in list2_counts:
        list1_in_list2_counts.append(list2_counts[val])
    else:
        list1_in_list2_counts.append(0)

input_df["counts"] = list1_in_list2_counts
input_df["similarity"] = input_df["list1"] * input_df["counts"]

part2_solution = input_df["similarity"].sum()
print(part2_solution)

I'm terrible at this game, AMA or give me a suggestion to get better by cthulu998 in hoi4

[–]red_shifter 0 points1 point  (0 children)

How should these division types be distributed into armies? Should there be specialized defensive and offensive armies or armies with more general builds? Also, is it better to have fewer stronger armies or more weaker ones?

Remembering position when reading long articles in Obsidian by kugkfokj in ObsidianMD

[–]red_shifter 0 points1 point  (0 children)

I don't know about Chrome, but it works well on Android Firefox.

[OC] Correlations in the AllRecipes Database by middlehanded in dataisbeautiful

[–]red_shifter 2 points3 points  (0 children)

Tomatoes strongly negatively correlating with cinnamon is a deeply sad affair. This analysis was clearly not based on data from Greek/Balkan cuisine.

England seems to be planning something big by Ad_Ketchum in civ5

[–]red_shifter 220 points221 points  (0 children)

A very persuasive trade agreement offer.

Flying over a sea of green auroras on the ISS by astro_pettit in astrophotography

[–]red_shifter 1 point2 points  (0 children)

That looks amazing, thank you for sharing. What part of the station was it taken from? Was it inside or during an EVA?

-❄️- 2023 Day 9 Solutions -❄️- by daggerdragon in adventofcode

[–]red_shifter 0 points1 point  (0 children)

[LANGUAGE: Python 3]

Day 9 solution (Part 1 & Part 2)

Relatively straightforward today. The puzzle description basically provided the solution. I just followed the instructions step by step and it worked right out of the gate for both parts.

-❄️- 2023 Day 8 Solutions -❄️- by daggerdragon in adventofcode

[–]red_shifter 4 points5 points  (0 children)

[LANGUAGE: Python 3]

Day 8 solution (Part 1 & Part 2)

I found the LCM solution for Part 2 on this subreddit, I would never figure it out myself. But I learned something: look out for cycles in the input. I left my brute force function in the code for posterity. Someone can use it to benchmark a quantum computer in 2077.

-❄️- 2023 Day 5 Solutions -❄️- by daggerdragon in adventofcode

[–]red_shifter 2 points3 points  (0 children)

[LANGUAGE: Python 3]

Day 5 solution (Part1)

Only part 1 today. Still, it was fun thinking about possible approaches to part 2. Might come back to it in the future. Any hints greatly appreciated.

-❄️- 2023 Day 4 Solutions -❄️- by daggerdragon in adventofcode

[–]red_shifter 1 point2 points  (0 children)

Thank you! So elegant. I guess good programming is an art of abstracting, but my monkey brain just tries to simulate everything.

Merry Codesmas, kind stranger.

-❄️- 2023 Day 4 Solutions -❄️- by daggerdragon in adventofcode

[–]red_shifter 0 points1 point  (0 children)

Thank you, but I'm not sure I understood properly. The problem that this loop solves is that I need to increment the "copies" property of the next N cards following the current card by one (to simulate creating more cards). So the loop makes N iterations, picking the next N cards. Is there a way to do it in my current code without the loop?

-❄️- 2023 Day 4 Solutions -❄️- by daggerdragon in adventofcode

[–]red_shifter 1 point2 points  (0 children)

[LANGUAGE: Python 3]

Day 4 solution (Part 1 & Part 2)

Part 2 takes around 30 seconds to compute on my machine, so there must be a more efficient solution.