1
0

Compare commits

..

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
16 changed files with 55 additions and 1243 deletions

View File

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

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 { 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 { loop {
let (x, y) = pos; 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; return false;
} else if next == block || '#' == m[next] { } else if next == block || '#' == m[next] {
// we only check for loops on a collision to speed things up // 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.contains(&(pos, dir)) {
if visited[pos][dir as usize % 5] {
return true; return true;
} }
visited[pos][dir as usize % 5] = true; visited.insert((pos, dir));
dir = match 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() { pub fn day_main() {
let input = read_to_string("input/day09.txt").unwrap(); let input = read_to_string("input/day09.txt").unwrap();
@@ -53,41 +53,48 @@ fn part1(input: &str) -> RiddleResult {
} }
fn part2(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) // (start_index, len, file_id)
let mut files: Vec<(usize, usize, usize)> = Vec::with_capacity(input.len() / 2 + 1); let mut files: Vec<(usize, u32, usize)> = Vec::with_capacity(input.len() / 2 + 1);
let mut head = 0;
for (i, l) in input.chars().enumerate() { for (i, l) in input.chars().enumerate() {
let l = l.to_digit(10).unwrap() as usize; let l = l.to_digit(10).unwrap();
if i % 2 == 0 { let content = if i % 2 == 0 {
files.push((head, l, i / 2)); // file
Some(i / 2) // id based on order of apperance and every second one is a file
} else { } else {
free.insert(head, l); None
};
if i % 2 == 0 {
files.push((disk.len(), l, i / 2));
}
for _ in 0..l {
disk.push(content);
} }
head += l;
} }
for file in files.iter_mut().rev() { while let Some((start_index, length, file_id)) = files.pop() {
let (start_index, length, _file_id) = *file; let mut seeker = 0;
let found = free let mut found = None;
.iter() while disk[seeker] != Some(file_id) {
.take_while(|f| *f.0 < start_index) if disk[seeker..seeker + length as usize]
.find(|f| *f.1 >= length); .iter()
.all(|v| v.is_none())
if let Some((&free_start, &free_length)) = found { {
free.remove(&free_start); found = Some(seeker);
free.insert(start_index, length); break;
file.0 = free_start; }
if length < free_length { seeker += 1;
free.insert(free_start + length, free_length - length); }
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 disk.into_iter()
.iter() .enumerate()
.map(|(start_index, l, file_id)| { .map(|(i, v)| if let Some(value) = v { i * value } else { 0 })
*file_id * (*start_index..start_index + l).sum::<RiddleResult>()
})
.sum() .sum()
} }

View File

@@ -56,12 +56,12 @@ fn part2(input: &str) -> RiddleResult {
} }
let mut area = 0; let mut area = 0;
let mut further = vec![p]; 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() { while let Some(current) = further.pop() {
if processed.contains(&current) { if processed.contains(&current) {
continue; continue;
} }
group.insert(current);
area += 1; area += 1;
for next in NEIGHBORS.iter().map(|d| (current.0 + d.0, current.1 + d.1)) { for next in NEIGHBORS.iter().map(|d| (current.0 + d.0, current.1 + d.1)) {
let next_c = garden.get(next); let next_c = garden.get(next);
@@ -71,88 +71,28 @@ fn part2(input: &str) -> RiddleResult {
} }
} }
processed.insert(current); 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 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)] #[cfg(test)]
mod test { mod test {
use std::collections::HashSet;
use crate::day12::sides;
use super::{part1, part2}; use super::{part1, part2};
const TEST_INPUT: &str = r"AAAA const TEST_INPUT: &str = r"AAAA
@@ -170,16 +110,4 @@ EEEC
fn test2() { fn test2() {
assert_eq!(part2(TEST_INPUT), 80); 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,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,62 +0,0 @@
use std::{fs::read_to_string, ops::BitXor};
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 = prune(mix(secret * 64, secret));
secret = prune(mix(secret / 32, secret));
secret = prune(mix(secret * 2048, secret))
}
secret
}
fn mix(value: i64, secret: i64) -> i64 {
value.bitxor(secret)
}
fn prune(value: i64) -> i64 {
value % 16777216
}
fn part2(_input: &str) -> RiddleResult {
0
}
#[cfg(test)]
mod test {
use super::{part1, part2};
const TEST_INPUT: &str = r"";
#[test]
fn test1() {
assert_eq!(
part1(
"1
10
100
2024
"
),
37327623
);
}
#[test]
fn test2() {
assert_eq!(part2(TEST_INPUT), 0);
}
}

View File

@@ -10,12 +10,5 @@ pub mod day09;
pub mod day10; pub mod day10;
pub mod day11; pub mod day11;
pub mod day12; pub mod day12;
pub mod day13;
pub mod day14;
pub mod day15;
pub mod day16;
pub mod day17;
pub mod day19;
pub mod day22;
// PLACEHOLDER // PLACEHOLDER
pub mod utils; pub mod utils;

View File

@@ -17,13 +17,6 @@ fn main() {
(10, day10::day_main), (10, day10::day_main),
(11, day11::day_main), (11, day11::day_main),
(12, day12::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),
(19, day19::day_main),
(22, day22::day_main),
// PLACEHOLDER // PLACEHOLDER
]); ]);
let day: Option<u8> = args().nth(1).and_then(|a| a.parse().ok()); let day: Option<u8> = args().nth(1).and_then(|a| a.parse().ok());

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> { pub fn map_values<U>(self, f: fn(T) -> U) -> Grid<U> {
let new_content = self.content.into_iter().map(f).collect_vec(); let new_content = self.content.into_iter().map(f).collect_vec();
Grid { 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> { impl Grid<char> {
pub fn parse(input: &str) -> Grid<char> { pub fn parse(input: &str) -> Grid<char> {
let content_width = input.lines().next().unwrap().len(); let content_width = input.lines().next().unwrap().len();
@@ -139,15 +115,6 @@ impl Grid<char> {
content, 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> { impl<T> Index<Coord> for Grid<T> {