1
0

1 Commits

Author SHA1 Message Date
738da8bc22 day 12 part 2 look for corners by two blueprints 2024-12-12 22:28:32 +01:00
23 changed files with 56 additions and 2267 deletions

View File

@@ -1,12 +1,8 @@
[package]
name = "advent-of-rust-2024"
version = "0.1.0"
edition = "2024"
edition = "2021"
[dependencies]
itertools = "0.13.0"
regex = "1.11.1"
[profile.dev]
opt-level = 3

View File

@@ -1,9 +1,3 @@
# Advent of Rust 2024
A few of the solutions for [Advent of Code 2024](https://adventofcode.com/2024) in Rust.
## Points
I finally (as of October 2025) finished all existing puzzles and am a part of the 500 star club!
![Screenshot from Advent of Code saying "Totals stars: 500"](assets/500stars.png)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

View File

@@ -1,67 +0,0 @@
def parse_input(input: list[str]):
return [tuple(map(lambda f: int(f), cl.split(','))) for cl in input]
with open('input/day18.txt', 'r') as f:
data = f.read()
points = parse_input(data.strip().split('\n'))
# points = set([
# (5, 4),
# (4, 2),
# (4, 5),
# (3, 0),
# (2, 1),
# (6, 3),
# (2, 4),
# (1, 5),
# (0, 6),
# (3, 3),
# (2, 6),
# (5, 1),
# (1, 2),
# (5, 5),
# (2, 5),
# (6, 5),
# (1, 4),
# (0, 4),
# (6, 4),
# (1, 1),
# (6, 1),
# (1, 0),
# (0, 5),
# (1, 6),
# (2, 0),
# ][:12])
# goal = (6, 6)
# w = 6
def sp(points, w):
visited = dict()
stack = [(0, 0, 0)]
while len(stack) > 0:
(x, y, c) = stack.pop(0)
if (x, y) == (w, w):
return c
if (x, y) in visited:
continue
visited[(x, y)] = c
for (a, b) in [(x+nx, y+ny) for (nx, ny) in [(0, 1), (1, 0), (0, -1), (-1, 0)]]:
if 0 <= a <= w and 0 <= b <= w and (a, b) not in points:
stack.append((a, b, c + 1))
return None
print("task 1: " + str(sp(set(points[:1024]), 70)))
for take in range(1024, len(points)):
solution = sp(set(points[:take]), 70)
if not solution:
print("task 2: " + str(points[take - 1]))
break

View File

@@ -1,57 +0,0 @@
def parse_input(input: list[str]):
l = [(x, y) for (y, line) in enumerate(input) for (x, c) in enumerate(line) if c == '#']
start = [(x, y) for (y, line) in enumerate(input) for (x, c) in enumerate(line) if c == 'S'][0]
goal = [(x, y) for (y, line) in enumerate(input) for (x, c) in enumerate(line) if c == 'E'][0]
w = max([x for (x, y) in l])
h = max([y for (x, y) in l])
return l, w, h, start, goal
def sssp(points, w, h, start):
visited = dict()
(sx, sy) = start
stack = [(sx, sy, 0)]
while len(stack) > 0:
(x, y, c) = stack.pop(0)
if (x, y) in visited:
continue
visited[(x, y)] = c
for (a, b) in [(x+nx, y+ny) for (nx, ny) in [(0, 1), (1, 0), (0, -1), (-1, 0)]]:
if 0 <= a <= w and 0 <= b <= w and (a, b) not in points:
stack.append((a, b, c + 1))
return visited
def mhd(a, b):
(xa, ya) = a
(xb, yb) = b
return abs(xa - xb) + abs(ya - yb)
def others(origin, max_distance):
(sx, sy) = origin
return [(a, b) for a in range(sx - max_distance, sx + max_distance + 1) for b in range(sy - max_distance, sy + max_distance + 1)]
def solve(points, threshold, cheat_length):
fromstart = sssp(set(points), w, h, start)
toend = sssp(set(points), w, h, goal)
cheatrange = range(2, cheat_length + 1)
return len([1 for a in fromstart for b in others(a, cheat_length) if mhd(a, b) in cheatrange and b in toend and fromstart[a] + mhd(a, b) + toend[b] <= threshold])
source = "input/day20.txt"
with open(source, 'r') as f:
data = f.read()
(points, w, h, start, goal) = parse_input(data.strip().split('\n'))
bottomline = sssp(set(points), w, h, start)[goal]
solution1 = solve(set(points), bottomline - 100, 2)
print("part 1: " + str(solution1))
solution2 = solve(set(points), bottomline - 100, 20)
print("part 2: " + str(solution2))

View File

@@ -64,7 +64,7 @@ fn parse(input: &str) -> (Grid<char>, Coord) {
}
fn is_loop(m: &Grid<char>, block: Coord, mut pos: Coord, mut dir: char) -> bool {
let mut visited: Grid<[bool; 5]> = Grid::from_default(m.content_width, m.content_height);
let mut visited = HashSet::new();
loop {
let (x, y) = pos;
@@ -79,11 +79,10 @@ fn is_loop(m: &Grid<char>, block: Coord, mut pos: Coord, mut dir: char) -> bool
return false;
} else if next == block || '#' == m[next] {
// we only check for loops on a collision to speed things up
// this is our own little hash function to speed things up
if visited[pos][dir as usize % 5] {
if visited.contains(&(pos, dir)) {
return true;
}
visited[pos][dir as usize % 5] = true;
visited.insert((pos, dir));
dir = match dir {
'^' => '>',

View File

@@ -1,4 +1,4 @@
use std::{collections::BTreeMap, fs::read_to_string};
use std::fs::read_to_string;
pub fn day_main() {
let input = read_to_string("input/day09.txt").unwrap();
@@ -53,41 +53,48 @@ fn part1(input: &str) -> RiddleResult {
}
fn part2(input: &str) -> RiddleResult {
let mut free: BTreeMap<usize, usize> = BTreeMap::new();
let mut disk = Vec::with_capacity(input.len() * 10);
// (start_index, len, file_id)
let mut files: Vec<(usize, usize, usize)> = Vec::with_capacity(input.len() / 2 + 1);
let mut head = 0;
let mut files: Vec<(usize, u32, usize)> = Vec::with_capacity(input.len() / 2 + 1);
for (i, l) in input.chars().enumerate() {
let l = l.to_digit(10).unwrap() as usize;
if i % 2 == 0 {
files.push((head, l, i / 2));
let l = l.to_digit(10).unwrap();
let content = if i % 2 == 0 {
// file
Some(i / 2) // id based on order of apperance and every second one is a file
} else {
free.insert(head, l);
None
};
if i % 2 == 0 {
files.push((disk.len(), l, i / 2));
}
head += l;
for _ in 0..l {
disk.push(content);
}
for file in files.iter_mut().rev() {
let (start_index, length, _file_id) = *file;
let found = free
}
while let Some((start_index, length, file_id)) = files.pop() {
let mut seeker = 0;
let mut found = None;
while disk[seeker] != Some(file_id) {
if disk[seeker..seeker + length as usize]
.iter()
.take_while(|f| *f.0 < start_index)
.find(|f| *f.1 >= length);
if let Some((&free_start, &free_length)) = found {
free.remove(&free_start);
free.insert(start_index, length);
file.0 = free_start;
if length < free_length {
free.insert(free_start + length, free_length - length);
.all(|v| v.is_none())
{
found = Some(seeker);
break;
}
seeker += 1;
}
if let Some(empty_start) = found {
for i in 0..length as usize {
disk[empty_start + i] = Some(file_id);
disk[start_index + i] = None;
}
}
}
files
.iter()
.map(|(start_index, l, file_id)| {
*file_id * (*start_index..start_index + l).sum::<RiddleResult>()
})
disk.into_iter()
.enumerate()
.map(|(i, v)| if let Some(value) = v { i * value } else { 0 })
.sum()
}

View File

@@ -56,12 +56,12 @@ fn part2(input: &str) -> RiddleResult {
}
let mut area = 0;
let mut further = vec![p];
let mut group = HashSet::new();
let mut convex_corners = 0;
let mut concave_corners = 0;
while let Some(current) = further.pop() {
if processed.contains(&current) {
continue;
}
group.insert(current);
area += 1;
for next in NEIGHBORS.iter().map(|d| (current.0 + d.0, current.1 + d.1)) {
let next_c = garden.get(next);
@@ -71,88 +71,28 @@ fn part2(input: &str) -> RiddleResult {
}
}
processed.insert(current);
for (da, db) in NEIGHBORS.iter().circular_tuple_windows() {
let a = (current.0 + da.0, current.1 + da.1);
let b = (current.0 + db.0, current.1 + db.1);
if garden.get(a) != Some(c) && garden.get(b) != Some(c) {
convex_corners += 1;
} else if garden.get(a) == Some(c)
&& garden.get(b) == Some(c)
&& garden.get((current.0 + da.0 + db.0, current.1 + da.1 + db.1)) != Some(c)
{
concave_corners += 1;
}
result += area * sides(group);
}
}
let var_name = convex_corners + concave_corners;
let var_name = area * (var_name);
result += var_name;
}
result
}
fn sides(group: HashSet<(i64, i64)>) -> RiddleResult {
let x_range = group.iter().min_by_key(|it| it.0).unwrap().0
..=group.iter().max_by_key(|it| it.0).unwrap().0;
let y_range = group.iter().min_by_key(|it| it.1).unwrap().1
..=group.iter().max_by_key(|it| it.1).unwrap().1;
let mut result = 0;
for x in x_range {
// 1 for the ending of the last group, +1 for each time a line "stops", e.g. between the current point and next there is a gap
let points = group
.iter()
.filter(|p| p.0 == x)
.filter(|p| !group.contains(&(p.0 - 1, p.1)))
.sorted_by_key(|p| p.1)
.collect_vec();
if !points.is_empty() {
let count = points
.into_iter()
.tuple_windows()
.filter(|(a, b)| a.1 + 1 != b.1)
.count();
result += 1 + count;
}
let points = group
.iter()
.filter(|p| p.0 == x)
.filter(|p| !group.contains(&(p.0 + 1, p.1)))
.sorted_by_key(|p| p.1)
.collect_vec();
if !points.is_empty() {
let count = points
.into_iter()
.tuple_windows()
.filter(|(a, b)| a.1 + 1 != b.1)
.count();
result += 1 + count;
}
}
for y in y_range {
let points = group
.iter()
.filter(|p| p.1 == y)
.filter(|p| !group.contains(&(p.0, p.1 - 1)))
.sorted_by_key(|p| p.0)
.collect_vec();
if !points.is_empty() {
let count = points
.into_iter()
.tuple_windows()
.filter(|(a, b)| a.0 + 1 != b.0)
.count();
result += 1 + count;
}
let points = group
.iter()
.filter(|p| p.1 == y)
.filter(|p| !group.contains(&(p.0, p.1 + 1)))
.sorted_by_key(|p| p.0)
.collect_vec();
if !points.is_empty() {
let count = points
.into_iter()
.tuple_windows()
.filter(|(a, b)| a.0 + 1 != b.0)
.count();
result += 1 + count;
}
}
result as RiddleResult
}
#[cfg(test)]
mod test {
use std::collections::HashSet;
use crate::day12::sides;
use super::{part1, part2};
const TEST_INPUT: &str = r"AAAA
@@ -170,16 +110,4 @@ EEEC
fn test2() {
assert_eq!(part2(TEST_INPUT), 80);
}
#[test]
fn sides_one() {
let group = HashSet::from_iter([(3, 5)]);
assert_eq!(sides(group), 4);
}
#[test]
fn sides_plus() {
let group = HashSet::from_iter([(3, 3), (3, 4), (3, 2), (2, 3), (4, 3)]);
assert_eq!(sides(group), 12);
}
}

View File

@@ -1,99 +0,0 @@
use std::fs::read_to_string;
use itertools::Itertools;
use regex::Regex;
pub fn day_main() {
let input = read_to_string("input/day13.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = i64;
fn part1(input: &str) -> RiddleResult {
// Button A: X+30, Y+84
// Button B: X+74, Y+60
// Prize: X=2358, Y=2628
let r = Regex::new(
r"Button A: X\+(\d+), Y\+(\d+)
Button B: X\+(\d+), Y\+(\d+)
Prize: X=(\d+), Y=(\d+)",
)
.unwrap();
r.captures_iter(input)
.map(|block| {
let (ax, ay, bx, by, px, py) = block
.iter()
.skip(1)
.map(|it| it.unwrap().as_str().parse::<i64>().unwrap())
.collect_tuple()
.unwrap();
solve((ax, ay, bx, by, px, py)).unwrap_or(0)
})
.sum()
}
fn part2(input: &str) -> RiddleResult {
let r = Regex::new(
r"Button A: X\+(\d+), Y\+(\d+)
Button B: X\+(\d+), Y\+(\d+)
Prize: X=(\d+), Y=(\d+)",
)
.unwrap();
r.captures_iter(input)
.map(|block| {
let (ax, ay, bx, by, px, py) = block
.iter()
.skip(1)
.map(|it| it.unwrap().as_str().parse::<i64>().unwrap())
.collect_tuple()
.unwrap();
let solution = solve((ax, ay, bx, by, px + 10000000000000, py + 10000000000000));
solution.unwrap_or(0)
})
.sum()
}
fn solve((ax, ay, bx, by, px, py): (i64, i64, i64, i64, i64, i64)) -> Option<RiddleResult> {
let b = (ay * px - ax * py) / (ay * bx - ax * by);
let a = (px - b * bx) / ax;
if a >= 0 && b >= 0 && a * ax + b * bx == px && a * ay + b * by == py {
Some(3 * a + b)
} else {
None
}
}
#[cfg(test)]
mod test {
use super::{part1, part2};
const TEST_INPUT: &str = r"Button A: X+94, Y+34
Button B: X+22, Y+67
Prize: X=8400, Y=5400
Button A: X+26, Y+66
Button B: X+67, Y+21
Prize: X=12748, Y=12176
Button A: X+17, Y+86
Button B: X+84, Y+37
Prize: X=7870, Y=6450
Button A: X+69, Y+23
Button B: X+27, Y+71
Prize: X=18641, Y=10279
";
#[test]
fn test1() {
assert_eq!(part1(TEST_INPUT), 480);
}
#[test]
fn test2() {
assert_eq!(part2(TEST_INPUT), 875318608908);
}
}

View File

@@ -1,153 +0,0 @@
use std::fs::read_to_string;
use itertools::Itertools;
use crate::utils::grid::Grid;
pub fn day_main() {
let input = read_to_string("input/day14.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = usize;
fn part1(input: &str) -> RiddleResult {
solve_part1(input, 100, 101, 103)
}
fn solve_part1(input: &str, rounds: i64, width: i64, height: i64) -> RiddleResult {
let mut robots = parse(input);
for _ in 0..rounds {
robots.iter_mut().for_each(|((px, py), (vx, vy))| {
*px = (*px + width + *vx) % width;
*py = (*py + height + *vy) % height;
});
}
let upper_left = robots
.iter()
.filter(|&&((px, py), _)| px < width / 2 && py < height / 2)
.count();
let lower_left = robots
.iter()
.filter(|&&((px, py), _)| px < width / 2 && py > height / 2)
.count();
let upper_right = robots
.iter()
.filter(|&&((px, py), _)| px > width / 2 && py < height / 2)
.count();
let lower_right = robots
.iter()
.filter(|&&((px, py), _)| px > width / 2 && py > height / 2)
.count();
upper_left * lower_left * upper_right * lower_right
}
fn parse(input: &str) -> Vec<((i64, i64), (i64, i64))> {
input
.lines()
.map(|line| {
line.strip_prefix("p=")
.unwrap()
.split(" v=")
.map(|s| {
s.split(",")
.map(|d| d.parse::<i64>().unwrap())
.collect_tuple::<(i64, i64)>()
.unwrap()
})
.collect_tuple()
.unwrap()
})
.collect_vec()
}
#[allow(unused)]
fn part2(input: &str) -> i64 {
let width = 101;
let height = 103;
let mut robots = parse(input);
let max_seconds = width * height;
for second in 0.. {
if second > max_seconds {
panic!("Seen all combinations but no christmas tree. So sad!");
}
let mut grid: Grid<u8> = Grid::from_default(101, 103);
robots.iter_mut().for_each(|((px, py), (vx, vy))| {
*px = (*px + width + *vx) % width;
*py = (*py + height + *vy) % height;
grid[(*px, *py)] += 1;
if let Some(v) = grid.get_mut((*px + 1, *py)) {
*v += 1
}
if let Some(v) = grid.get_mut((*px - 1, *py)) {
*v += 1
}
if let Some(v) = grid.get_mut((*px, *py + 1)) {
*v += 1
}
if let Some(v) = grid.get_mut((*px, *py - 1)) {
*v += 1
}
});
if robots.iter().filter(|(s, _)| grid[*s] > 1).count() > robots.len() * 70 / 100 {
// printr(&robots, width, height);
// println!("after {} seconds. Press enter to continue or type 'merry christmas' if you can spot a tree!", second + 1); //+1 because we look at it after they have changed
return second + 1;
// let stdin = io::stdin();
// let line = stdin.lock().lines().next().unwrap().unwrap();
// if line.as_str().eq_ignore_ascii_case("merry christmas") {
// return second + 1;
// }
}
}
unreachable!()
}
#[allow(unused)]
type Robot = ((i64, i64), (i64, i64));
#[allow(unused)]
fn printr(robots: &[Robot], width: i64, height: i64) {
for y in 0..height {
for x in 0..width {
let c = robots
.iter()
.filter(|&&((px, py), _)| px == x && py == y)
.count();
if c == 0 {
print!(".");
} else {
print!("{c}");
}
}
println!();
}
}
#[cfg(test)]
mod test {
use crate::day14::solve_part1;
const TEST_INPUT: &str = r"p=0,4 v=3,-3
p=6,3 v=-1,-3
p=10,3 v=-1,2
p=2,0 v=2,-1
p=0,0 v=1,3
p=3,0 v=-2,-2
p=7,6 v=-1,-3
p=3,0 v=-1,-2
p=9,3 v=2,3
p=7,3 v=-1,2
p=2,4 v=2,-3
p=9,5 v=-3,-3
";
#[test]
fn test1() {
assert_eq!(solve_part1(TEST_INPUT, 100, 11, 7), 12);
}
}

View File

@@ -1,203 +0,0 @@
use std::{collections::HashSet, fs::read_to_string};
use itertools::Itertools;
use crate::utils::grid::{Coord, Grid};
pub fn day_main() {
let input = read_to_string("input/day15.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = i64;
fn part1(input: &str) -> RiddleResult {
let (grid, movements) = input.split_once("\n\n").unwrap();
let mut grid = Grid::parse(grid);
let mut robot = grid.entries().find(|(_r, c)| **c == '@').unwrap().0;
let directions = |d| match d {
'^' => (0, -1),
'v' => (0, 1),
'<' => (-1, 0),
'>' => (1, 0),
_ => panic!(),
};
for m in movements.chars().filter(|c| *c != '\n') {
let dir = directions(m);
let space = (1..)
.map(|i| (robot.0 + i * dir.0, robot.1 + i * dir.1))
.take_while(|p| grid.get(*p).is_some() && (grid[*p] == '.' || grid[*p] == 'O'))
.find(|p| grid[*p] == '.');
if let Some(p) = space {
if (p.0 - robot.0).abs() + (p.1 - robot.1).abs() > 1 {
// this means: the free spot is not a direct neighbor of the robot, i.e. there are boxes
grid[p] = 'O';
}
grid[robot] = '.';
robot = (robot.0 + dir.0, robot.1 + dir.1);
grid[robot] = '@';
}
}
grid.entries()
.filter(|(_, c)| **c == 'O')
.map(|((x, y), _)| y * 100 + x)
.sum()
}
fn part2(input: &str) -> RiddleResult {
let (grid, movements) = input.split_once("\n\n").unwrap();
let grid = grid
.lines()
.map(|line| {
{
line.chars().flat_map(|c| {
match c {
'.' => "..",
'@' => "@.",
'#' => "##",
'O' => "[]",
_ => panic!(),
}
.chars()
})
}
.join("")
})
.join("\n");
let mut grid = Grid::parse(grid.as_str());
let mut robot = grid.entries().find(|(_r, c)| **c == '@').unwrap().0;
let directions = |d| match d {
'^' => (0, -1),
'v' => (0, 1),
'<' => (-1, 0),
'>' => (1, 0),
_ => panic!(),
};
for m in movements.chars().filter(|c| *c != '\n') {
let dir = directions(m);
if let Some(tiles_to_move) = movable(robot, dir, &grid, false) {
let old = tiles_to_move
.iter()
.map(|tile| (*tile, grid[*tile]))
.collect_vec();
tiles_to_move.iter().for_each(|tile| grid[*tile] = '.');
old.into_iter()
.for_each(|(tile, c)| grid[(tile.0 + dir.0, tile.1 + dir.1)] = c);
robot = (robot.0 + dir.0, robot.1 + dir.1);
}
}
grid.entries()
.filter(|(_, c)| **c == '[')
.map(|((x, y), _)| y * 100 + x)
.sum()
}
fn movable(
from: (i64, i64),
dir: (i64, i64),
grid: &Grid<char>,
ignore_other_half: bool,
) -> Option<HashSet<Coord>> {
match grid[from] {
'.' => Some(HashSet::new()),
'@' => {
let next = movable((from.0 + dir.0, from.1 + dir.1), dir, grid, false);
next.map(|mut v| {
v.insert(from);
v
})
}
'[' => {
if dir.0 != 0 {
// sideway movement is "regular"
let next = movable((from.0 + dir.0, from.1 + dir.1), dir, grid, false);
next.map(|mut v| {
v.insert(from);
v
})
} else {
// up/down always means the other part of the crate has to move in parallel
let mut next1 = movable((from.0 + dir.0, from.1 + dir.1), dir, grid, false)?;
if !ignore_other_half {
let next2 = movable((from.0 + 1, from.1), dir, grid, true)?;
next1.extend(next2);
}
next1.insert(from);
Some(next1)
}
}
']' => {
if dir.0 != 0 {
// sideway movement is "regular"
let next = movable((from.0 + dir.0, from.1 + dir.1), dir, grid, false);
next.map(|mut v| {
v.insert(from);
v
})
} else {
// up/down always means the other part of the crate has to move in parallel
let mut next1 = movable((from.0 + dir.0, from.1 + dir.1), dir, grid, false)?;
if !ignore_other_half {
let next2 = movable((from.0 - 1, from.1), dir, grid, true)?;
next1.extend(next2);
}
next1.insert(from);
Some(next1)
}
}
_ => None,
}
}
#[cfg(test)]
mod test {
use super::{part1, part2};
const TEST_INPUT: &str = r"########
#..O.O.#
##@.O..#
#...O..#
#.#.O..#
#...O..#
#......#
########
<^^>>>vv<v>>v<<";
const TEST_LARGE: &str = r"##########
#..O..O.O#
#......O.#
#.OO..O.O#
#..O@..O.#
#O#..O...#
#O..O..O.#
#.OO.O.OO#
#....O...#
##########
<vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><<><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^
vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v
><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv<
<<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^<vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^
^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>>^v><>^v><<<<v>>v<v<v>vvv>^<><<>^><
^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><<<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^
>^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^
<><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<>
^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v>
v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v><^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^
";
#[test]
fn test1() {
assert_eq!(part1(TEST_INPUT), 2028);
}
#[test]
fn test2() {
assert_eq!(part2(TEST_LARGE), 9021);
}
}

View File

@@ -1,190 +0,0 @@
use std::{
collections::{BinaryHeap, HashMap, HashSet},
fs::read_to_string,
};
use itertools::Itertools;
use crate::utils::grid::{Coord, Grid};
pub fn day_main() {
let input = read_to_string("input/day16.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = usize;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Dir {
N,
E,
S,
W,
}
impl Dir {
fn nexts(&self) -> [Self; 2] {
match self {
Dir::N | Dir::S => [Dir::W, Dir::E],
Dir::E | Dir::W => [Dir::S, Dir::N],
}
}
}
struct Step(Coord, Dir, usize, Option<Node>);
impl Ord for Step {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
other.2.cmp(&self.2)
}
}
impl PartialOrd for Step {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Step {
fn eq(&self, other: &Self) -> bool {
other.2.eq(&self.2)
}
}
impl Eq for Step {}
fn part1(input: &str) -> RiddleResult {
use Dir::*;
let maze = Grid::parse(input);
let start = maze.entries().find(|(_p, c)| **c == 'S').unwrap().0;
let end = maze.entries().find(|(_p, c)| **c == 'E').unwrap().0;
let mut visited = HashMap::<(Coord, Dir), usize>::new();
let mut stack: BinaryHeap<Step> = BinaryHeap::new();
stack.push(Step(start, E, 0, None));
while let Some(Step(np, nd, cost, _)) = stack.pop() {
if visited.contains_key(&(np, nd)) {
continue;
}
visited.insert((np, nd), cost);
if np == end {
return cost;
}
for d in nd.nexts() {
if !visited.contains_key(&(np, d)) {
stack.push(Step(np, d, cost + 1000, None));
}
}
let forward = match nd {
N => (np.0, np.1 - 1),
E => (np.0 + 1, np.1),
S => (np.0, np.1 + 1),
W => (np.0 - 1, np.1),
};
if maze[forward] != '#' && !visited.contains_key(&(forward, nd)) {
stack.push(Step(forward, nd, cost + 1, None));
}
}
panic!("no path found")
}
type Node = (Coord, Dir);
fn part2(input: &str) -> RiddleResult {
use Dir::*;
let maze = Grid::parse(input);
let start = maze.entries().find(|(_p, c)| **c == 'S').unwrap().0;
let end = maze.entries().find(|(_p, c)| **c == 'E').unwrap().0;
let mut visited = HashMap::<Node, (usize, Vec<Node>)>::new();
let mut stack: BinaryHeap<Step> = BinaryHeap::new();
stack.push(Step(start, E, 0, None));
let mut best: Option<usize> = None;
while let Some(Step(np, nd, cost, pred)) = stack.pop() {
if let Some(b) = best {
if b < cost {
break; // can't reach the end point with best cost anymore
}
}
let entry = visited.entry((np, nd)).or_insert_with(|| {
(
cost,
if let Some(pred) = pred {
vec![pred]
} else {
vec![]
},
)
});
if entry.0 < cost {
continue;
}
if let Some(pred) = pred {
entry.1.push(pred);
}
if np == end {
best = Some(cost);
}
for d in nd.nexts() {
if !visited.contains_key(&(np, d)) {
stack.push(Step(np, d, cost + 1000, Some((np, nd))));
}
}
let forward = match nd {
N => (np.0, np.1 - 1),
E => (np.0 + 1, np.1),
S => (np.0, np.1 + 1),
W => (np.0 - 1, np.1),
};
if maze[forward] != '#' && !visited.contains_key(&(forward, nd)) {
stack.push(Step(forward, nd, cost + 1, Some((np, nd))));
}
}
let mut accounted = HashSet::<Node>::new();
let mut stack: Vec<Node> = visited
.iter()
.filter(|((pos, _dir), _)| *pos == end)
.map(|(node, _)| *node)
.to_owned()
.collect_vec();
while let Some(node) = stack.pop() {
if accounted.contains(&node) {
continue;
}
accounted.insert(node);
for pred in visited[&node].1.iter() {
stack.push(*pred);
}
}
accounted.into_iter().map(|(pos, _)| pos).unique().count()
}
#[cfg(test)]
mod test {
use super::{part1, part2};
const TEST_INPUT: &str = r"###############
#.......#....E#
#.#.###.#.###.#
#.....#.#...#.#
#.###.#####.#.#
#.#.#.......#.#
#.#.#####.###.#
#...........#.#
###.#.#####.#.#
#...#.....#.#.#
#.#.#.###.#.#.#
#.....#...#.#.#
#.###.#.#.#.#.#
#S..#.....#...#
###############
";
#[test]
fn test1() {
assert_eq!(part1(TEST_INPUT), 7036);
}
#[test]
fn test2() {
assert_eq!(part2(TEST_INPUT), 45);
}
}

View File

@@ -1,142 +0,0 @@
use std::{fs::read_to_string, ops::BitXor};
use itertools::Itertools;
pub fn day_main() {
let input = read_to_string("input/day17.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = String;
fn part1(input: &str) -> RiddleResult {
let (a, b, c, program) = parse_input(input);
run(&program, a, b, c)
.into_iter()
.map(|it| it.to_string())
.join(",")
}
fn run(program: &Vec<i64>, mut a: i64, mut b: i64, mut c: i64) -> Vec<i64> {
let mut ip = 0;
let mut output = vec![];
while ip < program.len() {
let opcode = program[ip];
let operand = program[(ip + 1) % program.len()];
match opcode {
0 => a = a / (2i64.pow(val(a, b, c, operand) as u32)),
1 => b = b.bitxor(operand),
2 => b = val(a, b, c, operand) % 8,
3 => {
if a == 0 {
} else {
ip = operand as usize;
continue;
}
}
4 => b = b.bitxor(c),
5 => output.push(val(a, b, c, operand) % 8),
6 => b = a / (2i64.pow(val(a, b, c, operand) as u32)),
7 => c = a / (2i64.pow(val(a, b, c, operand) as u32)),
_ => panic!("illegal op code {}", opcode),
}
ip += 2;
}
output
}
fn parse_input(input: &str) -> (i64, i64, i64, Vec<i64>) {
let (first, second) = input.split_once("\n\n").unwrap();
let mut registers = first.lines().map(|line| line.split_once(": ").unwrap().1);
let a = registers.next().unwrap().parse::<i64>().unwrap();
let b = registers.next().unwrap().parse::<i64>().unwrap();
let c = registers.next().unwrap().parse::<i64>().unwrap();
let program = second
.split_once(": ")
.unwrap()
.1
.split(",")
.map(|v| v.parse::<i64>().unwrap())
.collect_vec();
(a, b, c, program)
}
fn val(a: i64, b: i64, c: i64, operand: i64) -> i64 {
match operand {
0..=3 => operand,
4 => a,
5 => b,
6 => c,
_ => panic!("illegal operand {}", operand),
}
}
fn part2(input: &str) -> RiddleResult {
let (_, _, _, program) = parse_input(input);
solve(&program, program.len() - 1, 0).unwrap().to_string()
}
fn solve(program: &Vec<i64>, index: usize, a: i64) -> Option<i64> {
// if index == 0 {
// return if &run(program, a, 0, 0) == program {
// Some(a)
// } else {
// None
// };
// }
for i in 0..8 {
let next_a = a * 8 + i;
let o = run(program, next_a, 0, 0);
if o[0] == program[index] {
if index == 0 {
return Some(next_a);
} else {
let m = solve(program, index - 1, next_a);
if m.is_some() {
return m;
}
}
}
}
None
}
#[cfg(test)]
mod test {
use super::{part1, part2};
const TEST_INPUT: &str = r"
Register A: 729
Register B: 0
Register C: 0
Program: 0,1,5,4,3,0
";
#[test]
fn test1() {
assert_eq!(part1(TEST_INPUT.trim()), "4,6,3,5,6,3,5,2,1,0".to_string());
}
#[test]
fn test2() {
assert_eq!(
part2(
"Register A: 2024
Register B: 0
Register C: 0
Program: 0,3,5,4,3,0
"
.trim()
),
"117440".to_string()
);
}
}

View File

@@ -1,147 +0,0 @@
use std::{collections::VecDeque, fs::read_to_string};
use itertools::Itertools;
use crate::utils::grid::Grid;
pub fn day_main() {
let input = read_to_string("input/day18.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = usize;
fn part1(input: &str) -> RiddleResult {
solve1(input, 1024, 70)
}
fn solve1(input: &str, n: usize, coord_max: i64) -> usize {
let points = parse(input);
sp(&points[..n], coord_max).unwrap()
}
fn sp(points: &[(i64, i64)], coord_max: i64) -> Option<usize> {
let mut pcheck = Grid::from_default(coord_max + 1, coord_max + 1);
for p in points {
pcheck.set(*p, true);
}
let mut visited = Grid::from_default(coord_max + 1, coord_max + 1);
let mut queue = VecDeque::from_iter([(0, 0, 0)]);
while let Some((x, y, c)) = queue.pop_front() {
if x == coord_max && y == coord_max {
return Some(c);
}
if visited.get((x, y)) == Some(&true) {
continue;
}
visited.set((x, y), true);
for (dx, dy) in [(0, 1), (1, 0), (0, -1), (-1, 0)] {
let (a, b) = (x + dx, y + dy);
if (0..=coord_max).contains(&a)
&& (0..=coord_max).contains(&b)
&& pcheck.get((a, b)) == Some(&false)
{
queue.push_back((a, b, c + 1));
}
}
}
None
}
fn parse(input: &str) -> Vec<(i64, i64)> {
input
.trim()
.lines()
.map(|line| {
line.split(",")
.map(|v| v.parse().unwrap())
.collect_tuple()
.unwrap()
})
.collect_vec()
}
fn part2(input: &str) -> String {
solve2(input, 1024, 70)
}
fn solve2(input: &str, fixed: usize, max_coord: i64) -> String {
let points = parse(input);
// we want the first point with which there is no shortest path
let mut i = fixed;
let mut jump = (points.len() - fixed) / 2;
#[cfg(debug_assertions)]
let mut loops = 0;
loop {
#[cfg(debug_assertions)]
{
loops += 1;
}
let l = sp(&points[..i - 1], max_coord);
let r = sp(&points[..i], max_coord);
if l.is_some() && r.is_none() {
#[cfg(debug_assertions)]
{
let iters_needed = i - fixed;
dbg!(loops, iters_needed);
}
return format!("{},{}", points[i - 1].0, points[i - 1].1);
}
if l.is_some() {
i += jump;
} else {
i -= jump;
}
jump /= 2;
if jump == 0 {
jump += 1;
}
}
}
#[cfg(test)]
mod test {
use crate::day18::{solve1, solve2};
const TEST_INPUT: &str = r"5,4
4,2
4,5
3,0
2,1
6,3
2,4
1,5
0,6
3,3
2,6
5,1
1,2
5,5
2,5
6,5
1,4
0,4
6,4
1,1
6,1
1,0
0,5
1,6
2,0
";
#[test]
fn test1() {
assert_eq!(solve1(TEST_INPUT, 12, 6), 22);
}
#[test]
fn test2() {
assert_eq!(solve2(TEST_INPUT, 12, 6), "6,1");
}
}

View File

@@ -1,98 +0,0 @@
use std::{
collections::{HashMap, HashSet},
fs::read_to_string,
};
pub fn day_main() {
let input = read_to_string("input/day19.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = usize;
fn part1(input: &str) -> RiddleResult {
let (a, b) = input.split_once("\n\n").unwrap();
let towels: HashSet<&str> = a.split(", ").collect();
b.lines().filter(|line| possible(line, &towels)).count()
}
fn possible(line: &str, towels: &HashSet<&str>) -> bool {
if line.is_empty() {
return true;
}
for t in towels.iter() {
if let Some(suffix) = line.strip_prefix(t) {
if possible(suffix, towels) {
return true;
}
}
}
false
}
fn countp<'a>(
line: &'a str,
towels: &HashSet<&str>,
solved: &mut HashMap<&'a str, usize>,
) -> usize {
if line.is_empty() {
return 1;
}
if let Some(count) = solved.get(line) {
return *count;
}
let mut summed = 0;
for t in towels.iter() {
if let Some(suffix) = line.strip_prefix(t) {
summed += countp(suffix, towels, solved);
}
}
solved.insert(line, summed);
summed
}
fn part2(input: &str) -> RiddleResult {
let (a, b) = input.split_once("\n\n").unwrap();
let towels: HashSet<&str> = a.split(", ").collect();
b.lines()
.map(|line| countp(line, &towels, &mut HashMap::new()))
.sum()
}
#[cfg(test)]
mod test {
use std::collections::HashSet;
use crate::day19::possible;
use super::{part1, part2};
const TEST_INPUT: &str = r"r, wr, b, g, bwu, rb, gb, br
brwrr
bggr
gbbr
rrbgbr
ubwu
bwurrg
brgr
bbrgwb
";
#[test]
fn test1() {
assert_eq!(part1(TEST_INPUT), 6);
}
#[test]
fn solver() {
let set = HashSet::from_iter(["r", "wr", "b", "g", "bwu", "rb", "gb", "br"]);
assert!(possible("bwurrg", &set));
}
#[test]
fn test2() {
assert_eq!(part2(TEST_INPUT), 16);
}
}

View File

@@ -1,299 +0,0 @@
use std::{collections::HashMap, fs::read_to_string};
use itertools::Itertools;
pub fn day_main() {
let input = read_to_string("input/day21.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = i64;
fn part1(input: &str) -> RiddleResult {
let mut p = Precomputed::new(2);
input
.lines()
.map(|line| p.shortest(line) * value(line))
.sum()
}
fn value(line: &str) -> i64 {
line[0..3].parse::<i64>().unwrap()
}
fn part2(input: &str) -> RiddleResult {
let mut p = Precomputed::new(25);
input
.lines()
.map(|line| p.shortest(line) * value(line))
.sum()
}
struct Precomputed {
num_sp: HashMap<(char, char), Vec<&'static str>>,
arrow_sp: HashMap<(char, char), Vec<&'static str>>,
robot_layers: i64,
cache: HashMap<(char, char, i64), i64>,
}
impl Precomputed {
fn new(robot_layers: i64) -> Self {
let num_sp = num_sp();
let arrow_sp = arrow_sp();
Self {
num_sp,
arrow_sp,
robot_layers,
cache: HashMap::new(),
}
}
fn shortest(&mut self, digit_pad: &str) -> RiddleResult {
format!("A{digit_pad}")
.chars()
.tuple_windows()
.map(|(a, b)| {
let x = self
.num_sp
.get(&(a, b))
.unwrap()
.clone()
.iter()
.map(|sp| format!("A{sp}A")) // we add the A in the next layer at the end of each sequence
.map(|sp| {
let x = if sp.len() > 1 {
sp.chars()
.tuple_windows()
.map(|(c, d)| self.get(c, d, self.robot_layers))
.sum::<i64>()
} else {
1
};
// println!(" sp {a} to {b} (NUM): {sp} -- {x}");
x
})
.min()
.unwrap();
// println!("{a}{b}: {x}");
x
})
// .inspect(|r| println!("shortest part: {r}"))
.sum()
}
fn get(&mut self, a: char, b: char, n: i64) -> i64 {
if n == 0 {
return 1;
}
if let Some(result) = self.cache.get(&(a, b, n)) {
return *result;
}
let paths = self.arrow_sp.get(&(a, b)).unwrap().clone();
let result = paths
.iter()
.map(|sp| format!("A{sp}A"))
.map(|sp| {
let x = if sp.len() > 1 {
sp.chars()
.tuple_windows()
.map(|(c, d)| self.get(c, d, n - 1))
.sum::<i64>()
} else {
1
};
// println!(
// "{}sp {a} to {b} ({n}): {sp} -- {x}",
// " ".repeat(self.robot_layers as usize + 2 - n as usize)
// );
x
})
.min()
.unwrap();
self.cache.insert((a, b, n), result);
result
}
}
fn arrow_sp() -> HashMap<(char, char), Vec<&'static str>> {
let mut starters = HashMap::new();
starters.insert(('A', '<'), vec!["<v<", "v<<"]);
starters.insert(('A', '^'), vec!["<"]);
starters.insert(('A', '>'), vec!["v"]);
starters.insert(('A', 'v'), vec!["<v", "v<"]);
starters.insert(('<', '^'), vec![">^"]);
starters.insert(('<', '>'), vec![">>"]);
starters.insert(('<', 'v'), vec![">"]);
starters.insert(('^', '>'), vec![">v", "v>"]);
starters.insert(('^', 'v'), vec!["v"]);
starters.insert(('>', 'v'), vec!["<"]);
let mut result = starters.clone();
for ((from, to), paths) in starters {
result.insert((to, from), invert(&paths));
}
for c in "A<>v^".chars() {
result.insert((c, c), vec![""]);
}
result
}
fn num_sp() -> HashMap<(char, char), Vec<&'static str>> {
let mut starters = HashMap::new();
starters.insert(('A', '0'), vec!["<"]);
starters.insert(('A', '1'), vec!["<^<", "^<<"]);
starters.insert(('A', '2'), vec!["<^", "^<"]);
starters.insert(('A', '3'), vec!["^"]);
starters.insert(('A', '4'), vec!["<^<^", "<^^<", "^<<^", "^<^<", "^^<<"]);
starters.insert(('A', '5'), vec!["<^^", "^<^", "^^<"]);
starters.insert(('A', '6'), vec!["^^"]);
starters.insert(
('A', '7'),
vec![
"<^<^^", "<^^<^", "<^^^<", "^<<^^", "^<^<^", "^<^^<", "^^^<<",
],
);
starters.insert(('A', '8'), vec!["<^^^", "^<^^", "^^<^", "^^^<"]);
starters.insert(('A', '9'), vec!["^^^"]);
starters.insert(('0', '1'), vec!["^<"]);
starters.insert(('0', '2'), vec!["^"]);
starters.insert(('0', '3'), vec!["^>", ">^"]);
starters.insert(('0', '4'), vec!["^<^", "^^<"]);
starters.insert(('0', '5'), vec!["^^"]);
starters.insert(('0', '6'), vec!["^^>", "^>^"]);
starters.insert(('0', '7'), vec!["^<^^", "^^<^", "^^^<"]);
starters.insert(('0', '8'), vec!["^^^"]);
starters.insert(('0', '9'), vec!["^^^>", "^^>^", "^>^^", ">^^^"]);
starters.insert(('1', '2'), vec![">"]);
starters.insert(('1', '3'), vec![">>"]);
starters.insert(('1', '4'), vec!["^"]);
starters.insert(('1', '5'), vec!["^>", ">^"]);
starters.insert(('1', '6'), vec!["^>>", ">^>", ">>^"]);
starters.insert(('1', '7'), vec!["^^"]);
starters.insert(('1', '8'), vec!["^^>", "^>^", ">^^"]);
starters.insert(('1', '9'), vec!["^^>>", "^>^>", "^>>^", ">^>^", ">>^^"]);
starters.insert(('2', '3'), vec![">"]);
starters.insert(('2', '4'), vec!["<^", "^<"]);
starters.insert(('2', '5'), vec!["^"]);
starters.insert(('2', '6'), vec!["^>", ">^"]);
starters.insert(('2', '7'), vec!["<^^", "^<^", "^^<"]);
starters.insert(('2', '8'), vec!["^^"]);
starters.insert(('2', '9'), vec!["^^>", "^>^", ">^^"]);
starters.insert(('3', '4'), vec!["<<^", "<^<", "^<<"]);
starters.insert(('3', '5'), vec!["<^", "^<"]);
starters.insert(('3', '6'), vec!["^"]);
starters.insert(
('3', '7'),
vec!["<<^^", "<^<^", "<^^<", "^<^<", "^<<^", "^^<<"],
);
starters.insert(('3', '8'), vec!["<^^", "^<^", "^^<"]);
starters.insert(('3', '9'), vec!["^^"]);
starters.insert(('4', '5'), vec![">"]);
starters.insert(('4', '6'), vec![">>"]);
starters.insert(('4', '7'), vec!["^"]);
starters.insert(('4', '8'), vec!["^>", ">^"]);
starters.insert(('4', '9'), vec!["^>>", ">^>", ">>^"]);
starters.insert(('5', '6'), vec![">"]);
starters.insert(('5', '7'), vec!["<^", "^<"]);
starters.insert(('5', '8'), vec!["^"]);
starters.insert(('5', '9'), vec!["^>", ">^"]);
starters.insert(('6', '7'), vec!["<<^", "<^<", "^<<"]);
starters.insert(('6', '8'), vec!["<^", "^<"]);
starters.insert(('6', '9'), vec!["^"]);
starters.insert(('7', '8'), vec![">"]);
starters.insert(('7', '9'), vec![">>"]);
starters.insert(('8', '9'), vec![">"]);
let mut result = starters.clone();
for ((from, to), paths) in starters {
result.insert((to, from), invert(&paths));
}
result
}
fn invert(paths: &Vec<&'static str>) -> Vec<&'static str> {
paths.iter().map(|path| reverse_path(path)).collect()
}
fn reverse_path(path: &str) -> &'static str {
path.chars()
.rev()
.map(|d| opposite(d))
.collect::<String>()
.leak()
}
fn opposite(d: char) -> char {
match d {
'<' => '>',
'^' => 'v',
'>' => '<',
'v' => '^',
_ => panic!("unknown direction {d}"),
}
}
#[cfg(test)]
mod test {
use crate::day21::Precomputed;
use super::{part1, part2};
const TEST_INPUT: &str = r"029A
980A
179A
456A
379A
";
#[test]
fn example1() {
assert_eq!(part1(TEST_INPUT), 126384);
}
#[test]
fn example1_mini() {
assert_eq!(part1("029A"), 68 * 29);
}
#[test]
fn shortest_human() {
let mut precomputed = Precomputed::new(2);
assert_eq!(precomputed.get('<', '^', 0), 1);
}
#[test]
fn shortest_1st() {
let mut p = Precomputed::new(2);
assert_eq!(p.get('A', '^', 1), 2);
}
#[test]
fn shortest_2nd() {
let mut p = Precomputed::new(2);
assert_eq!(p.get('A', '^', 2), 8);
}
#[test]
fn test2() {
assert_eq!(part2(TEST_INPUT), 0);
}
}

View File

@@ -1,126 +0,0 @@
use std::{
collections::{HashMap, HashSet},
fs::read_to_string,
ops::BitXor,
};
use itertools::Itertools;
pub fn day_main() {
let input = read_to_string("input/day22.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = i64;
fn part1(input: &str) -> RiddleResult {
input.lines().map(|is| solution(is.parse().unwrap())).sum()
}
fn solution(initial_secret: i64) -> i64 {
let mut secret = initial_secret;
for _ in 0..2000 {
secret = fun_name(secret);
}
secret
}
fn fun_name(secret: i64) -> i64 {
let secret = prune(mix(secret * 64, secret));
let secret = prune(mix(secret / 32, secret));
prune(mix(secret * 2048, secret))
}
fn mix(value: i64, secret: i64) -> i64 {
value.bitxor(secret)
}
fn prune(value: i64) -> i64 {
value % 16777216
}
fn part2(input: &str) -> RiddleResult {
let deltas = input
.trim()
.lines()
.map(|is| is.parse().unwrap())
.map(|s| generate(s))
.collect_vec();
let mut best = HashMap::new();
deltas.into_iter().for_each(|monkey| {
let mut seen = HashSet::new();
for (a, b, c, d) in monkey.iter().tuple_windows() {
let t = (a.delta, b.delta, c.delta, d.delta);
if !seen.contains(&t) {
seen.insert(t);
if !best.contains_key(&t) {
best.insert(t, 0);
}
best.entry(t).and_modify(|v| *v += d.price);
}
}
});
best.into_values().max().unwrap()
}
fn generate(start: i64) -> Vec<Foo> {
let mut result = Vec::with_capacity(2000);
result.push(Foo {
secret: start,
price: start % 10,
delta: -999999,
});
for i in 1..=2000 {
let prev = result[i - 1].secret;
let next = fun_name(prev);
let price = next % 10;
let delta = price - result[i - 1].price;
result.push(Foo {
secret: next,
price,
delta,
});
}
result
}
#[derive(Debug, PartialEq, Eq)]
struct Foo {
secret: i64,
price: i64,
delta: i64,
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test1() {
assert_eq!(
part1(
"1
10
100
2024
"
),
37327623
);
}
#[test]
fn test2() {
let input = "1
2
3
2024
";
assert_eq!(part2(input), 23);
}
}

View File

@@ -1,150 +0,0 @@
use std::{
collections::{HashMap, HashSet},
fs::read_to_string,
};
use itertools::Itertools;
pub fn day_main() {
let input = read_to_string("input/day23.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = usize;
fn part1(input: &str) -> RiddleResult {
let neighbours = make_graph(input);
let mut sets = vec![];
for a in neighbours.keys() {
for b in &neighbours[a] {
let common = neighbours[a].intersection(&neighbours[b]);
for c in common {
let mut v = vec![a, b, c];
v.sort_unstable();
sets.push(v);
}
}
}
let sets = sets.iter().unique().collect_vec();
sets.iter()
.filter(|set| set.iter().any(|t| t.starts_with("t")))
.count()
}
fn make_graph(input: &str) -> HashMap<&str, HashSet<&str>> {
let mut neighbours: HashMap<&str, HashSet<&str>> = HashMap::new();
input.lines().for_each(|line| {
let (a, b) = line.split_once("-").unwrap();
neighbours
.entry(a)
.and_modify(|list| {
list.insert(b);
})
.or_insert_with(|| HashSet::from([b]));
neighbours
.entry(b)
.and_modify(|list| {
list.insert(a);
})
.or_insert_with(|| HashSet::from([a]));
});
neighbours
}
fn part2(input: &str) -> String {
let graph = make_graph(input);
let mut best = "".to_string();
for a in graph.keys() {
let mut edge_counts = HashMap::<&str, u32>::new();
for b in &graph[a] {
edge_counts.entry(b).and_modify(|v| *v += 1).or_insert(1);
for c in &graph[b] {
edge_counts.entry(c).and_modify(|v| *v += 1).or_insert(1);
}
}
// now we have all counts for shared edges
// next, we find the highest number k for which there are k nodes which are connected to at least k other nodes
let mut k = *edge_counts.values().max().unwrap();
while k > 0 {
let nodes = edge_counts
.iter()
.filter(|(_, v)| **v >= k)
.map(|(k, _)| k)
.collect_vec();
if nodes.len() < (k + 1) as usize {
k -= 1;
continue;
}
// now we check if indeed all of the candidate nodes are connected
let found = nodes
.iter()
.filter(|&x| nodes.iter().all(|y| y == x || graph[*x].contains(*y)))
.sorted_unstable()
.join(",");
// disclaimer: this works for this input but not in general (think of a graph where a is in the middle and the other nodes in
// a circle around it, each connected to their left and right neighbour. There could be 10 nodes with degree 3 in there
// but ofc they wouldn't be all connected - so this "solution" would return nothing, althoug a max clique of
// size 3 would exist)
if found.len() > best.len() {
best = found;
}
break;
}
}
best
}
#[cfg(test)]
mod test {
use super::{part1, part2};
const TEST_INPUT: &str = r"kh-tc
qp-kh
de-cg
ka-co
yn-aq
qp-ub
cg-tb
vc-aq
tb-ka
wh-tc
yn-cg
kh-ub
ta-co
de-co
tc-td
tb-wq
wh-td
ta-ka
td-qp
aq-cg
wq-ub
ub-vc
de-ta
wq-aq
wq-vc
wh-yn
ka-de
kh-ta
co-tc
wh-qp
tb-vc
td-yn";
#[test]
fn test1() {
assert_eq!(part1(TEST_INPUT), 7);
}
#[test]
fn test2() {
assert_eq!(part2(TEST_INPUT), "co,de,ka,ta");
}
}

View File

@@ -1,225 +0,0 @@
use std::{collections::HashMap, fs::read_to_string, hash::Hash};
use itertools::Itertools;
pub fn day_main() {
let input = read_to_string("input/day24.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = u64;
fn part1(input: &str) -> RiddleResult {
let (a, b) = input.split_once("\n\n").unwrap();
let program = b
.lines()
.map(|l| {
let (lhs, rhs) = l.split_once(" -> ").unwrap();
(rhs, lhs)
})
.collect_map();
let start_values = a
.lines()
.map(|l| {
let (x, y) = l.split_once(": ").unwrap();
let b = match y {
"0" => false,
"1" => true,
_ => panic!("bad values {y}"),
};
(x, b)
})
.collect_map();
let binary_result = program
.keys()
.filter(|k| k.starts_with("z"))
.sorted_unstable()
.map(|z| compute(&program, &start_values, z))
.map(|b| match b {
true => "1",
false => "0",
})
.rev()
.join("");
u64::from_str_radix(&binary_result, 2).unwrap()
}
fn compute(program: &HashMap<&str, &str>, start_values: &HashMap<&str, bool>, start: &str) -> bool {
if start_values.contains_key(start) {
return start_values[start];
}
let v = program[start].split(" ").collect_vec();
let lhs = compute(program, start_values, v[0]);
let rhs = compute(program, start_values, v[2]);
match v[1] {
"AND" => lhs & rhs,
"OR" => lhs | rhs,
"XOR" => lhs ^ rhs,
_ => panic!("bad operator {}", v[1]),
}
}
const SWAPS: [(&'static str, &'static str); 4] = [
("rkf", "z09"),
("jgb", "z20"),
("vcg", "z24"),
("rvc", "rrs"),
];
fn swap(s: &str) -> &str {
for (a, b) in &SWAPS {
if *a == s {
return b;
}
if *b == s {
return a;
}
}
s
}
fn part2(input: &str) -> String {
let (_, b) = input.split_once("\n\n").unwrap();
let program = b
.lines()
.map(|l| l.split_once(" -> ").unwrap())
.map(|(def, name)| (def, swap(name)))
.collect_map();
if program["y00 XOR x00"] != "z00" {
panic!("first bit is bad already");
}
let Some(mut c_prev) = find(&program, "y00", "AND", "x00") else {
panic!("first carrier missing");
};
for i in 1..=44 {
// println!();
// println!("## {i:02}");
let x_i = format!("x{:02}", i);
let y_i = format!("y{:02}", i);
let op = "XOR";
let Some(xor_i) = find(&program, x_i.as_str(), op, y_i.as_str()) else {
println!("xor_{:02} missing", i);
break;
};
// println!("xor_i = {xor_i}");
let Some(z_i) = find(&program, &xor_i, "XOR", &c_prev) else {
println!("z_{:02} missing", i);
break;
};
if format!("z{i:02}") != z_i {
println!("z_i is bad: {z_i}");
break;
}
let Some(and_inputs_i) = find(&program, &x_i, "AND", &y_i) else {
println!("and_inputs_{:02} missing", i);
break;
};
// println!("and_inputs_i = {and_inputs_i}");
let Some(and_all_i) = find(&program, &c_prev, "AND", &xor_i) else {
println!("and of last carrier with xor_{:02} missing", i);
break;
};
// println!("and_all_i = {and_all_i}");
let Some(c_i) = find(&program, &and_all_i, "OR", &and_inputs_i) else {
println!("c_{:02} missing", i);
break;
};
// println!("c_i = {c_i}");
c_prev = c_i;
}
SWAPS
.iter()
.map(|(a, b)| [a, b])
.flatten()
.sorted()
.join(",")
}
fn find(program: &HashMap<&str, &str>, a: &str, op: &str, b: &str) -> Option<String> {
program
.get(format!("{a} {op} {b}").as_str())
.or_else(|| program.get(format!("{b} {op} {a}").as_str()))
.map(|s| s.to_string())
}
/// Trait that provides a `collect_map` method for iterators over key-value tuples.
pub trait CollectMap<K, V>: Iterator<Item = (K, V)>
where
K: Eq + Hash,
{
/// Collects the iterator into a `HashMap`.
fn collect_map(self) -> HashMap<K, V>;
}
// Blanket implementation for any compatible iterator
impl<I, K, V> CollectMap<K, V> for I
where
I: Iterator<Item = (K, V)>,
K: Eq + Hash,
{
fn collect_map(self) -> HashMap<K, V> {
self.collect()
}
}
#[cfg(test)]
mod test {
use super::part1;
const TEST_INPUT: &str = r"x00: 1
x01: 0
x02: 1
x03: 1
x04: 0
y00: 1
y01: 1
y02: 1
y03: 1
y04: 1
ntg XOR fgs -> mjb
y02 OR x01 -> tnw
kwq OR kpj -> z05
x00 OR x03 -> fst
tgd XOR rvg -> z01
vdt OR tnw -> bfw
bfw AND frj -> z10
ffh OR nrd -> bqk
y00 AND y03 -> djm
y03 OR y00 -> psh
bqk OR frj -> z08
tnw OR fst -> frj
gnj AND tgd -> z11
bfw XOR mjb -> z00
x03 OR x00 -> vdt
gnj AND wpb -> z02
x04 AND y00 -> kjc
djm OR pbm -> qhw
nrd AND vdt -> hwm
kjc AND fst -> rvg
y04 OR y02 -> fgs
y01 AND x02 -> pbm
ntg OR kjc -> kwq
psh XOR fgs -> tgd
qhw XOR tgd -> z09
pbm OR djm -> kpj
x03 XOR y03 -> ffh
x00 XOR y04 -> ntg
bfw OR bqk -> z06
nrd XOR fgs -> wpb
frj XOR qhw -> z04
bqk OR frj -> z07
y03 OR x01 -> nrd
hwm AND bqk -> z03
tgd XOR rvg -> z12
tnw OR pbm -> gnj";
#[test]
fn test1() {
assert_eq!(part1(TEST_INPUT), 2024);
}
}

View File

@@ -1,117 +0,0 @@
use std::fs::read_to_string;
use itertools::Itertools;
pub fn day_main() {
let input = read_to_string("input/day25.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
}
type RiddleResult = i64;
fn part1(input: &str) -> RiddleResult {
let (locks, keys): (Vec<_>, Vec<_>) = input
.split("\n\n")
.map(|item| {
let block = item
.lines()
.map(|line| line.chars().collect_vec())
.collect_vec();
let lock = block[0].contains(&'#');
let summary: (u8, u8, u8, u8, u8) = if lock {
// lock
(0..5)
.map(|x| {
(0..6)
.map(|y| block[y][x])
.enumerate()
.find(|(_, it)| *it == '.')
.unwrap_or((6, '.'))
.0 as u8
})
.collect_tuple()
.unwrap()
} else {
(0..5)
.map(|x| {
7 - ((0..6)
.map(|y| block[y][x])
.enumerate()
.find(|(_, it)| *it == '#')
.unwrap_or((6, '.'))
.0 as u8)
})
.collect_tuple()
.unwrap()
};
(lock, summary.0, summary.1, summary.2, summary.3, summary.4)
})
.partition(|s| s.0);
let mut matches = 0;
for lock in locks {
for &key in &keys {
if lock.1 + key.1 < 8
&& lock.2 + key.2 < 8
&& lock.3 + key.3 < 8
&& lock.4 + key.4 < 8
&& lock.5 + key.5 < 8
{
matches += 1;
}
}
}
matches
}
#[cfg(test)]
mod test {
use super::part1;
const TEST_INPUT: &str = r"#####
.####
.####
.####
.#.#.
.#...
.....
#####
##.##
.#.##
...##
...#.
...#.
.....
.....
#....
#....
#...#
#.#.#
#.###
#####
.....
.....
#.#..
###..
###.#
###.#
#####
.....
.....
.....
#....
#.#..
#.#.#
#####
";
#[test]
fn test1() {
assert_eq!(part1(TEST_INPUT), 3);
}
}

View File

@@ -10,17 +10,5 @@ pub mod day09;
pub mod day10;
pub mod day11;
pub mod day12;
pub mod day13;
pub mod day14;
pub mod day15;
pub mod day16;
pub mod day17;
pub mod day18;
pub mod day19;
pub mod day21;
pub mod day22;
pub mod day23;
pub mod day24;
pub mod day25;
// PLACEHOLDER
pub mod utils;

View File

@@ -17,33 +17,16 @@ fn main() {
(10, day10::day_main),
(11, day11::day_main),
(12, day12::day_main),
(13, day13::day_main),
(14, day14::day_main),
(15, day15::day_main),
(16, day16::day_main),
(17, day17::day_main),
(18, day18::day_main),
(19, day19::day_main),
(21, day21::day_main),
(22, day22::day_main),
(23, day23::day_main),
(23, day23::day_main),
(24, day24::day_main),
(25, day25::day_main),
// PLACEHOLDER
]);
let day: Option<u8> = args().nth(1).and_then(|a| a.parse().ok());
let Some(day) = day else {
let start = Instant::now();
mains
.iter()
.sorted_by_key(|entry| entry.0)
.for_each(|(d, f)| {
run(*d, f);
});
let duration = start.elapsed();
println!();
println!("{COLOR}{ITALIC}All tasks took {duration:?}{RESET_FORMATTING}");
return;
};

View File

@@ -89,15 +89,6 @@ impl<T> Grid<T> {
})
}
pub fn entries_mut(&mut self) -> impl Iterator<Item = (Coord, &mut T)> {
self.content.iter_mut().enumerate().map(|(i, val)| {
(
(i as i64 % self.content_width, i as i64 / self.content_width),
val,
)
})
}
pub fn map_values<U>(self, f: fn(T) -> U) -> Grid<U> {
let new_content = self.content.into_iter().map(f).collect_vec();
Grid {
@@ -108,21 +99,6 @@ impl<T> Grid<T> {
}
}
impl<T> Grid<T>
where
T: Default,
{
pub fn from_default(width: i64, height: i64) -> Grid<T> {
let mut content: Vec<T> = Vec::with_capacity((width * height) as usize);
content.resize_with((width * height) as usize, Default::default);
Grid {
content_width: width,
content_height: height,
content,
}
}
}
impl Grid<char> {
pub fn parse(input: &str) -> Grid<char> {
let content_width = input.lines().next().unwrap().len();
@@ -139,15 +115,6 @@ impl Grid<char> {
content,
}
}
pub fn print(&self) {
for line in &self.content.iter().chunks(self.content_width as usize) {
for c in line.into_iter() {
print!("{c}");
}
println!();
}
}
}
impl<T> Index<Coord> for Grid<T> {