1
0

Compare commits

...

37 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
1f4461a846 day 9 part 2 2024-12-09 21:28:02 +01:00
23b0aa1ff5 day 9 part 1 2024-12-09 08:31:50 +01:00
b987f56e5d fixed day 7 concat operator where rhs is 10^x 2024-12-08 18:12:12 +01:00
d1f49d204f day 8 part 2 2024-12-08 07:58:02 +01:00
a0c558032b day 8 part 1 2024-12-08 07:50:33 +01:00
19c60b98db day 7 speedup 2024-12-07 08:07:26 +01:00
af98c60972 day 7 cleanup 2024-12-07 07:23:00 +01:00
38e2a96a7a day 7 part 2 2024-12-07 07:18:33 +01:00
226a1fde49 day 7 part 1 2024-12-07 06:50:13 +01:00
2392539b6e option part for grid 2024-12-06 17:22:57 +01:00
345b29278f extended the grid with parsing from string and added position iterator 2024-12-06 16:09:20 +01:00
2d3443907d made coordinate public 2024-12-06 15:36:07 +01:00
2636f4a6c8 added grid utility and used it to speed up day 6 2024-12-06 15:33:57 +01:00
476f34e2b4 day 6 part 2 perf 2024-12-06 07:32:13 +01:00
9c5d12c6b0 day 6 part 2 performance 2024-12-06 07:19:24 +01:00
8157a9bf7e clippy 2024-12-06 06:36:58 +01:00
53854a13f4 day 6 part 2 2024-12-06 06:30:02 +01:00
f632977666 day 6 part 1 2024-12-06 06:20:41 +01:00
8cf59c3725 prepare day 6 2024-12-05 19:14:31 +01:00
1a4c40b8aa improve day 5 speed 2024-12-05 18:50:18 +01:00
fdd43c7953 clippy 2024-12-05 18:43:20 +01:00
ab88556e4c make day 5 faster 2024-12-05 18:40:12 +01:00
b5bcc8268f add elapsed time for each day to output 2024-12-05 18:33:45 +01:00
e8b494859b add elapsed time for each day to output 2024-12-05 18:30:51 +01:00
89b36dcb98 day 5 part 2 2024-12-05 18:09:10 +01:00
ac69934667 day 5 part 1 2024-12-05 18:08:22 +01:00
14 changed files with 1212 additions and 7 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"

120
src/day05.rs Normal file
View File

@@ -0,0 +1,120 @@
use itertools::Itertools;
use std::collections::HashSet;
use std::str::FromStr;
use std::{cmp::Ordering, fs::read_to_string};
pub fn day_main() {
let input = read_to_string("input/day05.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type R = usize;
fn part1(input: &str) -> R {
let (rules, books) = parse(input);
books
.iter()
.filter(|book| valid_book(book, &rules))
.map(|book| book[book.len() / 2])
.sum()
}
fn valid_book(book: &[R], rules: &HashSet<(R, R)>) -> bool {
for (i, a) in book.iter().enumerate() {
for b in book.iter().skip(i + 1) {
if rules.contains(&(*b, *a)) {
return false;
}
}
}
true
}
fn parse(input: &str) -> (HashSet<(R, R)>, Vec<Vec<R>>) {
let (a, b) = input.split_once("\n\n").unwrap();
let rules = a
.lines()
.map(|line| line.split_once("|").unwrap())
.map(|(a, b)| (R::from_str(a).unwrap(), R::from_str(b).unwrap()))
.collect();
let books = b
.lines()
.map(|line| line.split(",").flat_map(R::from_str).collect_vec())
.collect_vec();
(rules, books)
}
fn part2(input: &str) -> R {
let (rules, books) = parse(input);
books
.iter()
.filter(|book| !valid_book(book, &rules))
.map(|book| fix(book, &rules))
.map(|book| book[book.len() / 2])
.sum()
}
fn fix(book: &[R], rules: &HashSet<(R, R)>) -> Vec<R> {
let mut b = book.iter().copied().collect_vec();
b.sort_unstable_by(|a, b| {
if rules.contains(&(*a, *b)) {
Ordering::Less
} else if rules.contains(&(*b, *a)) {
Ordering::Greater
} else {
Ordering::Equal
}
});
b
}
#[cfg(test)]
mod test {
use super::{part1, part2, valid_book};
use std::collections::HashSet;
const TEST_INPUT: &str = r"47|53
97|13
97|61
97|47
75|29
61|13
75|53
29|13
97|29
53|29
61|53
97|53
61|29
47|13
75|47
97|75
47|61
75|61
47|29
75|13
53|13
75,47,61,53,29
97,61,53,29,13
75,29,13
75,97,47,61,53
61,13,29
97,13,75,29,47
";
#[test]
fn test1() {
assert!(valid_book(&[97, 5, 13], &HashSet::from([(97, 13)])));
assert!(!valid_book(&[13, 5, 97], &HashSet::from([(97, 13)])));
assert_eq!(part1(TEST_INPUT), 143);
}
#[test]
fn test2() {
assert_eq!(part2(TEST_INPUT), 123);
}
}

125
src/day06.rs Normal file
View File

@@ -0,0 +1,125 @@
use std::{collections::HashSet, fs::read_to_string};
use crate::utils::grid::{Coord, Grid};
pub fn day_main() {
let input = read_to_string("input/day06.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = usize;
fn part1(input: &str) -> RiddleResult {
let (m, pos) = parse(input);
let dir = '^';
let visited = get_visited(&m, pos, dir);
visited.len()
}
fn get_visited(m: &Grid<char>, mut pos: Coord, mut dir: char) -> HashSet<Coord> {
let mut visited = HashSet::new();
while m.contains_key(pos) {
let (x, y) = pos;
visited.insert(pos);
let next = match dir {
'^' => (x, y - 1),
'v' => (x, y + 1),
'<' => (x - 1, y),
'>' => (x + 1, y),
_ => unreachable!(),
};
if m.contains_key(next) && '#' == m[next] {
dir = match dir {
'^' => '>',
'v' => '<',
'<' => '^',
'>' => 'v',
_ => unreachable!("asdf"),
};
} else {
pos = next;
}
}
visited
}
fn part2(input: &str) -> RiddleResult {
let (m, pos) = parse(input);
let dir = '^';
get_visited(&m, pos, dir)
.into_iter()
.filter(|open| is_loop(&m, *open, pos, dir))
.count()
}
fn parse(input: &str) -> (Grid<char>, Coord) {
let mut m = Grid::parse(input);
let start = m.entries().find(|(_, c)| **c == '^').unwrap().0;
m[start] = '.';
(m, start)
}
fn is_loop(m: &Grid<char>, block: Coord, mut pos: Coord, mut dir: char) -> bool {
let mut visited = HashSet::new();
loop {
let (x, y) = pos;
let next = match dir {
'^' => (x, y - 1),
'v' => (x, y + 1),
'<' => (x - 1, y),
'>' => (x + 1, y),
_ => unreachable!(),
};
if !m.contains_key(next) {
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)) {
return true;
}
visited.insert((pos, dir));
dir = match dir {
'^' => '>',
'v' => '<',
'<' => '^',
'>' => 'v',
_ => unreachable!("asdf"),
};
} else {
pos = next;
}
}
}
#[cfg(test)]
mod test {
use super::{part1, part2};
const TEST_INPUT: &str = r"....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...
";
#[test]
fn test1() {
assert_eq!(part1(TEST_INPUT), 41);
}
#[test]
fn test2() {
assert_eq!(part2(TEST_INPUT), 6);
}
}

135
src/day07.rs Normal file
View File

@@ -0,0 +1,135 @@
use std::fs::read_to_string;
use itertools::Itertools;
use regex::Regex;
pub fn day_main() {
let input = read_to_string("input/day07.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = i64;
fn part1(input: &str) -> RiddleResult {
let regex = Regex::new("(\\d+)").unwrap();
input
.lines()
.map(|line| {
regex
.find_iter(line)
.map(|capture| capture.as_str().parse::<i64>().unwrap())
.collect_vec()
})
.filter(|v| well_calibrated(v))
.map(|v| v[0])
.sum()
}
fn well_calibrated(list: &[i64]) -> bool {
let expected = list[0];
let operands = list.iter().skip(1).copied().collect_vec();
let operators = ops(operands.len() - 1);
for ops in operators.into_iter() {
let v = ops
.into_iter()
.zip(operands.iter().skip(1))
.fold(operands[0], |acc, (op, val)| match op {
'*' => acc * val,
'+' => acc + val,
_ => panic!(),
});
if v == expected {
return true;
}
}
false
}
fn ops(n: usize) -> Vec<Vec<char>> {
if n == 1 {
return vec![vec!['+'], vec!['*']];
}
let v = ops(n - 1);
v.into_iter()
.flat_map(|vector| {
let mut v1 = vector.clone();
let mut v2 = vector;
v1.push('+');
v2.push('*');
[v1, v2]
})
.collect_vec()
}
fn part2(input: &str) -> RiddleResult {
let regex = Regex::new("(\\d+)").unwrap();
input
.lines()
.map(|line| {
regex
.find_iter(line)
.map(|capture| capture.as_str().parse::<i64>().unwrap())
.collect_vec()
})
.filter(|v| well(v[0], v[1], &v[2..]))
.map(|v| v[0])
.sum()
}
fn well(expected: i64, acc: i64, operands: &[i64]) -> bool {
if operands.is_empty() {
return expected == acc;
}
if acc > expected {
return false;
}
let next = operands[0];
let remainder = &operands[1..];
let v_mul = acc * next;
let v_plus = acc + next;
let v_concat = concat(acc, next);
well(expected, v_mul, remainder)
|| well(expected, v_plus, remainder)
|| well(expected, v_concat, remainder)
}
fn concat(lhs: i64, rhs: i64) -> i64 {
let exp: u32 = (rhs as f64 + 1.0).log10().ceil() as u32;
let shift = 10i64.pow(exp);
lhs * shift + rhs
}
#[cfg(test)]
mod test {
use super::{concat, part1, part2};
const TEST_INPUT: &str = r"190: 10 19
3267: 81 40 27
83: 17 5
156: 15 6
7290: 6 8 6 15
161011: 16 10 13
192: 17 8 14
21037: 9 7 18 13
292: 11 6 16 20";
#[test]
fn test1() {
assert_eq!(part1(TEST_INPUT), 3749);
}
#[test]
fn test2() {
assert_eq!(part2(TEST_INPUT), 11387);
}
#[test]
fn test_concat() {
assert_eq!(1234, concat(12, 34));
assert_eq!(1210, concat(12, 10));
}
}

107
src/day08.rs Normal file
View File

@@ -0,0 +1,107 @@
use std::{collections::HashSet, fs::read_to_string};
use itertools::Itertools;
use crate::utils::grid::Grid;
pub fn day_main() {
let input = read_to_string("input/day08.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = usize;
fn part1(input: &str) -> RiddleResult {
let grid = Grid::parse(input);
let mut antinodes = HashSet::new();
let antennas = grid
.entries()
.filter(|(_, c)| **c != '.')
.into_group_map_by(|(_, c)| *c);
for (_, coords) in antennas {
for (a, _) in coords.iter() {
for (b, _) in coords.iter() {
if a == b {
continue;
}
let dx = a.0 - b.0;
let dy = a.1 - b.1;
let p = (a.0 + dx, a.1 + dy);
if grid.contains_key(p) {
antinodes.insert(p);
}
}
}
}
antinodes.len()
}
fn part2(input: &str) -> RiddleResult {
let grid = Grid::parse(input);
let mut antinodes = HashSet::new();
let antennas = grid
.entries()
.filter(|(_, c)| **c != '.')
.into_group_map_by(|(_, c)| *c);
for (_, coords) in antennas {
for (a, _) in coords.iter() {
for (b, _) in coords.iter() {
if a == b {
continue;
}
antinodes.insert(*a);
antinodes.insert(*b);
let dx = a.0 - b.0;
let dy = a.1 - b.1;
for i in 1.. {
let p = (a.0 + i * dx, a.1 + i * dy);
if grid.contains_key(p) {
antinodes.insert(p);
} else {
break;
}
}
for i in 1.. {
let p = (a.0 - i * dx, a.1 - i * dy);
if grid.contains_key(p) {
antinodes.insert(p);
} else {
break;
}
}
}
}
}
antinodes.len()
}
#[cfg(test)]
mod test {
use super::{part1, part2};
const TEST_INPUT: &str = r"............
........0...
.....0......
.......0....
....0.......
......A.....
............
............
........A...
.........A..
............
............
";
#[test]
fn test1() {
assert_eq!(part1(TEST_INPUT), 14);
}
#[test]
fn test2() {
assert_eq!(part2(TEST_INPUT), 34);
}
}

116
src/day09.rs Normal file
View File

@@ -0,0 +1,116 @@
use std::fs::read_to_string;
pub fn day_main() {
let input = read_to_string("input/day09.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = usize;
fn part1(input: &str) -> RiddleResult {
let mut disk = Vec::with_capacity(input.len() * 10);
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
};
for _ in 0..l {
disk.push(content);
}
}
// dbg!(disk);
let mut free = disk
.iter()
.enumerate()
.find(|(_, v)| v.is_none())
.unwrap()
.0;
let mut last_block = disk.len() - 1;
while free < last_block {
if disk[free].is_some() {
break;
}
disk[free] = disk[last_block];
disk[last_block] = None;
while last_block > 0 && disk[last_block].is_none() {
last_block -= 1;
}
while free < disk.len() && disk[free].is_some() {
free += 1;
}
}
disk.into_iter()
.take(free)
.enumerate()
.map(|(i, v)| i * v.unwrap())
.sum()
}
fn part2(input: &str) -> RiddleResult {
let mut disk = Vec::with_capacity(input.len() * 10);
// (start_index, len, file_id)
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();
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
};
if i % 2 == 0 {
files.push((disk.len(), l, i / 2));
}
for _ in 0..l {
disk.push(content);
}
}
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;
}
}
}
disk.into_iter()
.enumerate()
.map(|(i, v)| if let Some(value) = v { i * value } else { 0 })
.sum()
}
#[cfg(test)]
mod test {
use super::{part1, part2};
const TEST_INPUT: &str = r"2333133121414131402";
#[test]
fn test1() {
assert_eq!(part1(TEST_INPUT), 1928);
}
#[test]
fn test2() {
assert_eq!(part2(TEST_INPUT), 2858);
}
}

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

@@ -2,3 +2,13 @@ pub mod day01;
pub mod day02;
pub mod day03;
pub mod day04;
pub mod day05;
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

@@ -1,7 +1,7 @@
use std::{collections::HashMap, env::args};
use advent_of_rust_2024::*;
use itertools::Itertools;
use std::time::Instant;
use std::{collections::HashMap, env::args};
fn main() {
let mains: HashMap<u8, fn() -> ()> = HashMap::from_iter([
@@ -9,6 +9,15 @@ fn main() {
(2, day02::day_main),
(3, day03::day_main),
(4, day04::day_main),
(5, day05::day_main),
(6, day06::day_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 {
@@ -16,8 +25,7 @@ fn main() {
.iter()
.sorted_by_key(|entry| entry.0)
.for_each(|(d, f)| {
println!("Day {d}:");
f();
run(*d, f);
});
return;
};
@@ -31,6 +39,17 @@ fn main() {
return;
};
println!("Day {day}:");
f();
run(day, f);
}
fn run(d: u8, f: &fn()) {
println!("Day {d}:");
let start = Instant::now();
f();
let duration = start.elapsed();
println!("{COLOR}{ITALIC}Took {duration:?}{RESET_FORMATTING}");
}
const COLOR: &str = "\x1b[38;5;247m";
const ITALIC: &str = "\x1b[3m";
const RESET_FORMATTING: &str = "\x1b[0m";

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));

230
src/utils/grid.rs Normal file
View File

@@ -0,0 +1,230 @@
use std::{
collections::HashMap,
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, Clone)]
pub struct Grid<T> {
pub content_width: i64,
pub content_height: i64,
content: Vec<T>,
}
pub type Coord = (i64, i64);
impl<T> Grid<T> {
pub fn from(mut source: HashMap<Coord, T>) -> Grid<T> {
let x_max = source.keys().max_by_key(|c| c.0).unwrap().0;
let y_max = source.keys().max_by_key(|c| c.1).unwrap().1;
let content_width = x_max + 1;
let content_height = y_max + 1;
let mut content = Vec::with_capacity((content_width * content_height) as usize);
for y in 0..content_height {
for x in 0..content_width {
let v = source
.remove(&(x, y))
.unwrap_or_else(|| panic!("no entry for {x}, {y}"));
content.push(v);
}
}
Grid {
content_width,
content_height,
content,
}
}
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)])
} else {
None
}
}
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])
} else {
None
}
}
pub fn set(&mut self, c: Coord, value: T) {
let index_of = self.index_of(c);
self.content[index_of] = value;
}
pub fn contains_key(&self, c: Coord) -> bool {
0 <= c.0 && c.0 < self.content_width && 0 <= c.1 && c.1 < self.content_height
}
pub fn entries(&self) -> impl Iterator<Item = (Coord, &T)> {
self.content.iter().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 {
content_width: self.content_width,
content_height: self.content_height,
content: new_content,
}
}
}
impl Grid<char> {
pub fn parse(input: &str) -> Grid<char> {
let content_width = input.lines().next().unwrap().len();
let mut content_height = 0;
let mut content = vec![];
for line in input.lines() {
content_height += 1;
content.reserve(content_width);
line.chars().for_each(|v| content.push(v));
}
Grid {
content_width: content_width as i64,
content_height,
content,
}
}
}
impl<T> Index<Coord> for Grid<T> {
type Output = T;
#[inline]
fn index(&self, index: Coord) -> &Self::Output {
&self.content[self.index_of(index)]
}
}
impl<T> IndexMut<Coord> for Grid<T> {
fn index_mut(&mut self, index: Coord) -> &mut Self::Output {
let index_of = self.index_of(index);
&mut self.content[index_of]
}
}
#[cfg(test)]
mod test {
use itertools::Itertools;
use super::Grid;
use std::collections::HashMap;
#[test]
fn init_and_read() {
let grid: Grid<char> = Grid::from(HashMap::from_iter([
((0, 0), '.'),
((0, 1), '.'),
((1, 0), '.'),
((1, 1), '#'),
]));
assert_eq!('.', grid[(0, 0)]);
assert_eq!('.', grid[(0, 1)]);
assert_eq!('.', grid[(1, 0)]);
assert_eq!('#', grid[(1, 1)]);
}
#[test]
fn mutate_by_index() {
let mut grid = generate();
grid[(0, 1)] = 'x';
assert_eq!('x', grid[(0, 1)]);
}
#[test]
fn mutate_option() {
let mut grid = generate();
if let Some(value) = grid.get_mut((0, 1)) {
*value = 'x';
}
assert_eq!('x', grid[(0, 1)]);
}
fn generate() -> Grid<char> {
let grid: Grid<char> = Grid::from(HashMap::from_iter([
((0, 0), '.'),
((0, 1), '.'),
((1, 0), '.'),
((1, 1), '.'),
]));
grid
}
#[test]
fn from_str() {
let s = "..\n.x";
let m_str = Grid::parse(s);
let mut m_gen = generate();
m_gen[(1, 1)] = 'x';
assert_eq!(m_gen, m_str);
}
#[test]
fn entries() {
let v = vec![
((0, 0), &'.'),
((1, 0), &'.'),
((0, 1), &'.'),
((1, 1), &'.'),
];
assert_eq!(v, generate().entries().collect_vec());
}
#[should_panic]
#[test]
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)));
}
#[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)]);
}
}

1
src/utils/mod.rs Normal file
View File

@@ -0,0 +1 @@
pub mod grid;