1
0

Compare commits

..

14 Commits

Author SHA1 Message Date
d2986b0134 day 6 part 2 1.5 times faster 2024-12-15 22:39:32 +01:00
d938e3a57c day 14 part 2 removed hashset for loop check 2024-12-15 17:30:17 +01:00
e135a6a349 disable day 14 part 2 because it requires manual intervention 2024-12-15 17:22:55 +01:00
c1abd8d8f8 day 15 part 2 2024-12-15 13:21:04 +01:00
24386b750b day 15 part 1 2024-12-15 11:26:29 +01:00
37874ebba9 day 14 make faster
cleanup

cleanup
2024-12-15 11:26:29 +01:00
0fd7b96791 day 9 cleanup 2024-12-14 15:22:25 +01:00
8c63bd2341 day 9 faster 2024-12-14 15:07:51 +01:00
cb41e4db56 disable day 14 part 2 because it requires manual intervention 2024-12-14 13:30:19 +01:00
f273c1719c clippy 2024-12-14 13:29:03 +01:00
267816b70e day 14 part 2 2024-12-14 10:30:17 +01:00
43003def6b day 14 part 1 2024-12-14 08:57:16 +01:00
0d910e8724 day 13 part 2 2024-12-13 15:32:45 +01:00
43bf93773f day 13 part 1 2024-12-13 13:26:52 +01:00
10 changed files with 618 additions and 54 deletions

View File

@@ -6,3 +6,7 @@ edition = "2021"
[dependencies]
itertools = "0.13.0"
regex = "1.11.1"
[profile.dev]
opt-level = 3

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 = HashSet::new();
let mut visited: Grid<[bool; 5]> = Grid::from_default(m.content_width, m.content_height);
loop {
let (x, y) = pos;
@@ -79,10 +79,11 @@ 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
if visited.contains(&(pos, dir)) {
// this is our own little hash function to speed things up
if visited[pos][dir as usize % 5] {
return true;
}
visited.insert((pos, dir));
visited[pos][dir as usize % 5] = true;
dir = match dir {
'^' => '>',

View File

@@ -1,4 +1,4 @@
use std::fs::read_to_string;
use std::{collections::BTreeMap, fs::read_to_string};
pub fn day_main() {
let input = read_to_string("input/day09.txt").unwrap();
@@ -53,48 +53,41 @@ fn part1(input: &str) -> RiddleResult {
}
fn part2(input: &str) -> RiddleResult {
let mut disk = Vec::with_capacity(input.len() * 10);
let mut free: BTreeMap<usize, usize> = BTreeMap::new();
// (start_index, len, file_id)
let mut files: Vec<(usize, u32, usize)> = Vec::with_capacity(input.len() / 2 + 1);
let mut files: Vec<(usize, usize, usize)> = Vec::with_capacity(input.len() / 2 + 1);
let mut head = 0;
for (i, l) in input.chars().enumerate() {
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 {
None
};
let l = l.to_digit(10).unwrap() as usize;
if i % 2 == 0 {
files.push((disk.len(), l, i / 2));
}
for _ in 0..l {
disk.push(content);
files.push((head, l, i / 2));
} else {
free.insert(head, l);
}
head += l;
}
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()
.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;
for file in files.iter_mut().rev() {
let (start_index, length, _file_id) = *file;
let found = free
.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);
}
}
}
disk.into_iter()
.enumerate()
.map(|(i, v)| if let Some(value) = v { i * value } else { 0 })
files
.iter()
.map(|(start_index, l, file_id)| {
*file_id * (*start_index..start_index + l).sum::<RiddleResult>()
})
.sum()
}

View File

@@ -56,12 +56,12 @@ fn part2(input: &str) -> RiddleResult {
}
let mut area = 0;
let mut further = vec![p];
let mut convex_corners = 0;
let mut concave_corners = 0;
let mut group = HashSet::new();
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,28 +71,88 @@ 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;
}
}
}
let var_name = convex_corners + concave_corners;
let var_name = area * (var_name);
result += var_name;
result += area * sides(group);
}
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
@@ -110,4 +170,16 @@ 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);
}
}

99
src/day13.rs Normal file
View File

@@ -0,0 +1,99 @@
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);
}
}

153
src/day14.rs Normal file
View File

@@ -0,0 +1,153 @@
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);
}
}

203
src/day15.rs Normal file
View File

@@ -0,0 +1,203 @@
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

@@ -10,5 +10,8 @@ pub mod day09;
pub mod day10;
pub mod day11;
pub mod day12;
pub mod day13;
pub mod day14;
pub mod day15;
// PLACEHOLDER
pub mod utils;

View File

@@ -17,6 +17,9 @@ 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),
// PLACEHOLDER
]);
let day: Option<u8> = args().nth(1).and_then(|a| a.parse().ok());

View File

@@ -89,6 +89,15 @@ 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 {
@@ -99,6 +108,21 @@ 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();
@@ -115,6 +139,15 @@ 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> {