1
0

Compare commits

...

11 Commits

Author SHA1 Message Date
738da8bc22 day 12 part 2 look for corners by two blueprints 2024-12-12 22:28:32 +01:00
dce8b1d2d5 clippy and cleanup 2024-12-12 18:47:22 +01:00
6621a5a71a day 12 part 2 2024-12-12 18:43:15 +01:00
0d0bcb2b33 day 12 part 1 2024-12-12 08:47:08 +01:00
3f94690477 day 11 a bit faster 2024-12-11 21:12:37 +01:00
3cab145b01 day 11 2024-12-11 20:03:06 +01:00
6946298ed7 added script for new day 2024-12-10 20:53:31 +01:00
934dc5cb7f added mapping to grid 2024-12-10 19:19:04 +01:00
ba78690ba4 fixed grid boundary checks 2024-12-10 19:06:07 +01:00
cef02c1f73 day 10 part 2 2024-12-10 06:53:04 +01:00
0b6f6fd3ec day 10 part 1 2024-12-10 06:46:53 +01:00
8 changed files with 391 additions and 6 deletions

32
newday.sh Executable file
View File

@@ -0,0 +1,32 @@
#!/bin/bash
# Check if the correct number of arguments is provided
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <two_digit_number>"
exit 1
fi
# Get the parameters
X="$1"
# Validate that X is a two-digit number
if ! [[ "$X" =~ ^[0-9]{2}$ ]]; then
echo "Error: The parameter must be a two-digit number."
exit 1
fi
cp src/template.rs src/day$X.rs
git add src/day$X.rs
touch input/day$X.txt
# Define the placeholder you want to replace
PLACEHOLDER="{{day}}"
# Use sed to replace the placeholder with the desired text
sed -i "s|$PLACEHOLDER|$X|g" "src/day$X.rs"
sed -i "s/.*\/\/ PLACEHOLDER.*/pub mod day$X;\n\/\/ PLACEHOLDER/" "src/lib.rs"
sed -i "s/.*\/\/ PLACEHOLDER.*/($X, day$X::day_main),\n\/\/ PLACEHOLDER/" "src/main.rs"
cargo fmt
echo "seems allright. created template for day $X"

141
src/day10.rs Normal file
View File

@@ -0,0 +1,141 @@
use std::{
collections::{HashMap, HashSet},
fs::read_to_string,
};
use itertools::Itertools;
use crate::utils::grid::Grid;
pub fn day_main() {
let input = read_to_string("input/day10.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input)); // 832 wrong
println!(" part2: {}", part2(input));
}
type RiddleResult = usize;
fn part1(input: &str) -> RiddleResult {
solve(input, true)
}
fn solve(input: &str, visit_once: bool) -> usize {
let grid = Grid::parse(input);
let m: HashMap<(i64, i64), u32> = HashMap::from_iter(grid.entries().map(|((x, y), c)| {
(
(x, y),
if *c == '.' {
1000
} else {
c.to_digit(10).unwrap()
},
)
}));
let grid = Grid::from(m);
let trail_heads = grid.entries().filter(|(_, h)| **h == 0).collect_vec();
let mut result = 0;
for (th, th_height) in trail_heads {
let mut count = 0;
let mut visited = HashSet::new();
let mut queue = vec![(th, th_height)];
while let Some((p, h)) = queue.pop() {
if visit_once && visited.contains(&(p, h)) {
continue;
}
visited.insert((p, h));
if *h == 9 {
count += 1;
continue;
}
let nexts = vec![
(p.0, p.1 + 1),
(p.0, p.1 - 1),
(p.0 + 1, p.1),
(p.0 - 1, p.1),
];
for next in nexts {
if let Some(nh) = grid.get(next) {
if *nh == h + 1 {
queue.push((next, nh));
}
}
}
}
result += count;
}
result
}
fn part2(input: &str) -> RiddleResult {
solve(input, false)
}
#[cfg(test)]
mod test {
use super::{part1, part2};
const TEST_INPUT: &str = r"89010123
78121874
87430965
96549874
45678903
32019012
01329801
10456732";
#[test]
fn test1() {
assert_eq!(part1(TEST_INPUT), 36);
}
#[test]
fn test1a() {
assert_eq!(
part1(
r"0123
1234
8765
9876
"
),
1
);
}
#[test]
fn test1b() {
assert_eq!(
part1(
r"...0...
...1...
...2...
6543456
7.....7
8.....8
9.....9
"
),
2
);
}
#[test]
fn test2() {
assert_eq!(
part2(
r".....0.
..4321.
..5..2.
..6543.
..7..4.
..8765.
..9....
"
),
3
);
}
}

56
src/day11.rs Normal file
View File

@@ -0,0 +1,56 @@
use std::{collections::HashMap, fs::read_to_string};
pub fn day_main() {
let input = read_to_string("input/day11.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = usize;
fn part1(input: &str) -> RiddleResult {
solve(input, 25)
}
fn solve(input: &str, blinks: i32) -> usize {
let mut stones: HashMap<usize, usize> =
input.split(" ").map(|v| (v.parse().unwrap(), 1)).collect();
let mut next = HashMap::new();
for _ in 0..blinks {
for (k, v) in stones {
if k == 0 {
next.entry(1).and_modify(|count| *count += v).or_insert(v);
} else if (k.ilog10() + 1) % 2 == 0 {
let l = (k.ilog10() + 1) / 2;
let z: usize = 10usize.pow(l);
let a = k / z;
let b = k % z;
next.entry(a).and_modify(|count| *count += v).or_insert(v);
next.entry(b).and_modify(|count| *count += v).or_insert(v);
} else {
let k_new = k * 2024;
next.entry(k_new)
.and_modify(|count| *count += v)
.or_insert(v);
}
}
stones = next;
next = HashMap::new();
}
stones.values().to_owned().sum()
}
fn part2(input: &str) -> RiddleResult {
solve(input, 75)
}
#[cfg(test)]
mod test {
use super::part1;
#[test]
fn test1() {
assert_eq!(part1("125 17"), 55312);
}
}

113
src/day12.rs Normal file
View File

@@ -0,0 +1,113 @@
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/day12.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = u64;
const NEIGHBORS: &[Coord] = &[(1, 0), (0, 1), (-1, 0), (0, -1)];
fn part1(input: &str) -> RiddleResult {
let garden = Grid::parse(input);
let mut processed: HashSet<Coord> = HashSet::new();
let mut result = 0;
for (p, c) in garden.entries() {
if processed.contains(&p) {
continue;
}
let mut area = 0;
let mut fence = 0;
let mut further = vec![p];
while let Some(current) = further.pop() {
if processed.contains(&current) {
continue;
}
area += 1;
for next in NEIGHBORS.iter().map(|d| (current.0 + d.0, current.1 + d.1)) {
let next_c = garden.get(next);
if next_c.is_none() || next_c.unwrap() != c {
fence += 1;
} else {
further.push(next);
}
}
processed.insert(current);
}
result += area * fence;
}
result
}
fn part2(input: &str) -> RiddleResult {
let garden = Grid::parse(input);
let mut processed: HashSet<Coord> = HashSet::new();
let mut result = 0;
for (p, c) in garden.entries() {
if processed.contains(&p) {
continue;
}
let mut area = 0;
let mut further = vec![p];
let mut convex_corners = 0;
let mut concave_corners = 0;
while let Some(current) = further.pop() {
if processed.contains(&current) {
continue;
}
area += 1;
for next in NEIGHBORS.iter().map(|d| (current.0 + d.0, current.1 + d.1)) {
let next_c = garden.get(next);
if next_c.is_none() || next_c.unwrap() != c {
} else {
further.push(next);
}
}
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
}
#[cfg(test)]
mod test {
use super::{part1, part2};
const TEST_INPUT: &str = r"AAAA
BBCD
BBCC
EEEC
";
#[test]
fn test1() {
assert_eq!(part1(TEST_INPUT), 140);
}
#[test]
fn test2() {
assert_eq!(part2(TEST_INPUT), 80);
}
}

View File

@@ -7,4 +7,8 @@ pub mod day06;
pub mod day07;
pub mod day08;
pub mod day09;
pub mod day10;
pub mod day11;
pub mod day12;
// PLACEHOLDER
pub mod utils;

View File

@@ -14,6 +14,10 @@ fn main() {
(7, day07::day_main),
(8, day08::day_main),
(9, day09::day_main),
(10, day10::day_main),
(11, day11::day_main),
(12, day12::day_main),
// PLACEHOLDER
]);
let day: Option<u8> = args().nth(1).and_then(|a| a.parse().ok());
let Some(day) = day else {

View File

@@ -1,7 +1,7 @@
use std::fs::read_to_string;
pub fn day_main() {
let input = read_to_string("input/dayXX.txt").unwrap();
let input = read_to_string("input/day{{day}}.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));

View File

@@ -3,11 +3,13 @@ use std::{
ops::{Index, IndexMut},
};
use itertools::Itertools;
/// A grid structure, indexed by (x, y) tuples. The top-left coordinate is (0, 0).
#[derive(Eq, PartialEq, Debug)]
#[derive(Eq, PartialEq, Debug, Clone)]
pub struct Grid<T> {
content_width: i64,
content_height: i64,
pub content_width: i64,
pub content_height: i64,
content: Vec<T>,
}
@@ -36,10 +38,19 @@ impl<T> Grid<T> {
}
fn index_of(&self, c: Coord) -> usize {
if !self.contains_key(c) {
panic!(
"point {c:?} out of range (width: {}, height: {})",
self.content_width, self.content_height
);
}
(c.1 * self.content_width + c.0) as usize
}
pub fn get(&self, c: Coord) -> Option<&T> {
if !self.contains_key(c) {
return None;
}
let index = self.index_of(c);
if index < self.content.len() {
Some(&self.content[self.index_of(c)])
@@ -49,6 +60,9 @@ impl<T> Grid<T> {
}
pub fn get_mut(&mut self, c: Coord) -> Option<&mut T> {
if !self.contains_key(c) {
return None;
}
let index = self.index_of(c);
if index < self.content.len() {
Some(&mut self.content[index])
@@ -73,7 +87,15 @@ impl<T> Grid<T> {
val,
)
})
// .collect_vec()
}
pub fn map_values<U>(self, f: fn(T) -> U) -> Grid<U> {
let new_content = self.content.into_iter().map(f).collect_vec();
Grid {
content_width: self.content_width,
content_height: self.content_height,
content: new_content,
}
}
}
@@ -179,10 +201,16 @@ mod test {
#[should_panic]
#[test]
fn out_of_bounds_panics() {
fn out_of_bounds_panics1() {
generate()[(-1, 3)];
}
#[should_panic]
#[test]
fn out_of_bounds_panics2() {
generate()[(1, 3)];
}
#[test]
fn option_success() {
assert_eq!(Some(&'.'), generate().get((0, 0)));
@@ -192,4 +220,11 @@ mod test {
fn option_out_of_bounds() {
assert_eq!(None, generate().get((30, 0)));
}
#[test]
fn value_mapping() {
let a: Grid<char> = generate();
let b: Grid<String> = a.map_values(|old| format!("{old}string"));
assert_eq!(".string".to_string(), b[(0, 0)]);
}
}