1
0

Compare commits

93 Commits

Author SHA1 Message Date
85de6b1539 day 18 performance improvement 2025-10-21 15:00:51 +02:00
944faf2159 dbg made nicer 2025-10-21 11:33:48 +02:00
d25a45cb52 day 18 part 2 faster with binary search 2025-10-21 11:29:29 +02:00
2d34e77b13 runner 2025-10-21 11:10:59 +02:00
0e5d98d1bc day 18 rust part 2 2025-10-20 23:49:10 +02:00
318643632e day 18 rust part 1 2025-10-20 23:20:20 +02:00
1c668afb4e fixed test compilation 2025-10-20 22:54:41 +02:00
2225c6c3e4 readme update 2025-10-14 19:13:32 +02:00
e659074a05 day 21 part 2 2025-10-14 18:51:13 +02:00
aad74883a2 day 21 part 1 2025-10-14 18:36:58 +02:00
20242ad04c day 25 2025-07-31 19:47:57 +02:00
06c2ceb96c day 22 part 2 performance mooooore 2025-07-30 22:39:25 +02:00
c38977eb15 day 22 part 2 performance 2025-07-30 22:35:17 +02:00
b75a35a4c1 day 22 part 2 2025-07-30 21:24:19 +02:00
0482402173 day 24 part 2 2025-07-07 23:08:37 +02:00
bf0fe46110 Disclaimer for day23.2 solution 2025-07-06 16:18:52 +02:00
329162a126 day 24 part 1 2025-07-06 11:43:31 +02:00
a451ba2ade day 23 part 2 2025-07-06 10:48:22 +02:00
07b03f31e1 day 23 part 1 2025-07-05 16:15:25 +02:00
6e850188a7 Ryst edition upgrade 2025-02-23 13:21:46 +01:00
db3cc66878 day 22 part 1 2025-01-18 17:42:25 +01:00
2c08f637b7 day 20 part 2 python 2024-12-21 13:05:09 +01:00
052a11762c day 20 part 1 python 2024-12-21 09:31:02 +01:00
455d17f0a6 day 18 part 2 python 2024-12-20 23:47:24 +01:00
a765ed1965 day 18 part 1 python 2024-12-20 23:31:24 +01:00
b4aaa7857f day 19 part 2 2024-12-19 20:07:39 +01:00
ee224046a6 day 19 part 1 2024-12-19 19:58:55 +01:00
0c3ebf803f day 17 part 2 2024-12-18 17:57:49 +01:00
878104d5f3 day 17 part 1 2024-12-17 19:01:15 +01:00
1469d51ba7 day 16 part 2 speedup x2 2024-12-16 21:25:30 +01:00
fbc80cac85 day 16 part 2 2024-12-16 12:47:16 +01:00
fd3629acfd day 16 part 1
day 16 part 1
2024-12-16 12:32:59 +01:00
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
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
9ab3453b02 cleanup 2024-12-04 07:03:13 +01:00
1f638fc7c7 day 4 part 2 2024-12-04 06:51:35 +01:00
2b7f894030 day 4 part 1 2024-12-04 06:44:17 +01:00
0e9a64e991 Prepare day 4 and template. 2024-12-03 06:55:12 +01:00
38eae3237a shortened bit more 2024-12-03 06:38:48 +01:00
af3bb05817 output formatting 2024-12-03 06:31:21 +01:00
e09b221a59 shortened day 3 part 2 2024-12-03 06:30:21 +01:00
f872d60381 cleanup 2024-12-03 06:25:49 +01:00
328d695e30 clippy 2024-12-03 06:19:56 +01:00
84c562b5a8 day 3 part 2 2024-12-03 06:17:37 +01:00
6b5aed016b day 3 part 1 2024-12-03 06:17:23 +01:00
36 changed files with 3663 additions and 22 deletions

45
Cargo.lock generated
View File

@@ -7,6 +7,16 @@ name = "advent-of-rust-2024"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"itertools", "itertools",
"regex",
]
[[package]]
name = "aho-corasick"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
"memchr",
] ]
[[package]] [[package]]
@@ -23,3 +33,38 @@ checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [ dependencies = [
"either", "either",
] ]
[[package]]
name = "memchr"
version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
name = "regex"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"

View File

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

View File

@@ -1,3 +1,9 @@
# Advent of Rust 2024 # Advent of Rust 2024
A few of the solutions for [Advent of Code 2024](https://adventofcode.com/2024) in Rust. 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)

BIN
assets/500stars.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

67
day18.py Normal file
View File

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

57
day20.py Normal file
View File

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

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"

View File

@@ -3,8 +3,8 @@ use std::fs::read_to_string;
pub fn day_main() { pub fn day_main() {
let input = read_to_string("input/day01.txt").unwrap(); let input = read_to_string("input/day01.txt").unwrap();
println!("part1: {}", part1(&input)); println!(" part1: {}", part1(&input));
println!("part2: {}", part2(&input)); println!(" part2: {}", part2(&input));
} }
type Int = i32; type Int = i32;

View File

@@ -4,8 +4,8 @@ use itertools::Itertools;
pub fn day_main() { pub fn day_main() {
let input = read_to_string("input/day02.txt").unwrap(); let input = read_to_string("input/day02.txt").unwrap();
println!("part1: {}", part1(&input)); println!(" part1: {}", part1(&input));
println!("part2: {}", part2(&input)); println!(" part2: {}", part2(&input));
} }
fn part1(input: &str) -> usize { fn part1(input: &str) -> usize {

View File

@@ -2,34 +2,60 @@ use std::fs::read_to_string;
pub fn day_main() { pub fn day_main() {
let input = read_to_string("input/day03.txt").unwrap(); let input = read_to_string("input/day03.txt").unwrap();
println!("part1: {}", part1(&input)); let input = input.trim();
println!("part2: {}", part2(&input)); println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
} }
type RiddleResult = usize; type RiddleResult = i64;
fn part1(input: &str) -> RiddleResult { fn part1(input: &str) -> RiddleResult {
0 let r = regex::Regex::new(r"mul\((\d{1,3}),(\d{1,3})\)").unwrap();
r.captures_iter(input)
.map(|c| {
let a: i64 = c[1].parse().unwrap();
let b: i64 = c[2].parse().unwrap();
a * b
})
.sum()
} }
fn part2(_input: &str) -> RiddleResult { fn part2(input: &str) -> RiddleResult {
0 let r = regex::Regex::new(r"do\(\)|don't\(\)|mul\((\d{1,3}),(\d{1,3})\)").unwrap();
r.captures_iter(input)
// (enabled, result): initially enabled; sum up the result over all enabled multiplications
.fold((true, 0), |(enabled, result), c| {
let s = c.get(0).unwrap().as_str();
match s {
"do()" => (true, result),
"don't()" => (false, result),
_ => {
let a: i64 = c[1].parse().unwrap();
let b: i64 = c[2].parse().unwrap();
(enabled, result + if enabled { a * b } else { 0 })
}
}
})
.1
} }
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::{part1, part2}; use super::{part1, part2};
const TEST_INPUT: &str = r" const TEST_INPUT: &str =
"; r"xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))";
const TEST_INPUT2: &str =
r"xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))";
#[test] #[test]
fn test1() { fn test1() {
assert_eq!(part1(TEST_INPUT), 0); assert_eq!(part1(TEST_INPUT), 161);
} }
#[test] #[test]
fn test2() { fn test2() {
assert_eq!(part2(TEST_INPUT), 0); assert_eq!(part2(TEST_INPUT2), 48);
} }
} }

116
src/day04.rs Normal file
View File

@@ -0,0 +1,116 @@
use itertools::Itertools;
use std::collections::HashMap;
use std::fs::read_to_string;
pub fn day_main() {
let input = read_to_string("input/day04.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = usize;
fn part1(input: &str) -> RiddleResult {
let puzzle = parse_map(input);
let mut count = 0;
let x_max = puzzle.keys().map(|k| k.0).max().unwrap();
let y_max = puzzle.keys().map(|k| k.1).max().unwrap();
for sx in 0..=x_max {
for sy in 0..=y_max {
'foo: for (a, b) in [
(1, 1),
(-1, 1),
(1, -1),
(-1, -1),
(0, 1),
(1, 0),
(0, -1),
(-1, 0),
] {
for (i, c) in "XMAS".chars().enumerate() {
let i = i as i32;
let p = (sx as i32 + i * a, sy as i32 + i * b);
if p.0 < 0 || p.1 < 0 || p.0 > x_max as i32 || p.1 > y_max as i32 {
continue 'foo;
}
if puzzle[&(p.0 as usize, p.1 as usize)] != c {
continue 'foo;
}
}
count += 1;
}
}
}
count
}
fn part2(input: &str) -> RiddleResult {
let puzzle = parse_map(input);
let mut count = 0;
let x_max = puzzle.keys().map(|k| k.0).max().unwrap();
let y_max = puzzle.keys().map(|k| k.1).max().unwrap();
for sx in 1..x_max {
for sy in 1..y_max {
let first = [
puzzle[&(sx - 1, sy - 1)],
puzzle[&(sx, sy)],
puzzle[&(sx + 1, sy + 1)],
]
.into_iter()
.join("");
let second = [
puzzle[&(sx - 1, sy + 1)],
puzzle[&(sx, sy)],
puzzle[&(sx + 1, sy - 1)],
]
.into_iter()
.join("");
if (first == "MAS" || first == "SAM") && (second == "SAM" || second == "MAS") {
count += 1;
}
}
}
count
}
fn parse_map(input: &str) -> HashMap<(usize, usize), char> {
let mut puzzle = HashMap::<(usize, usize), char>::new();
input.lines().enumerate().for_each(|(y, line)| {
line.chars().enumerate().for_each(|(x, chr)| {
puzzle.insert((x, y), chr);
})
});
puzzle
}
#[cfg(test)]
mod test {
use super::{part1, part2};
const TEST_INPUT: &str = r"MMMSXXMASM
MSAMXMSMSA
AMXSXMAAMM
MSAMASMSMX
XMASAMXAMM
XXAMMXXAMA
SMSMSASXSS
SAXAMASAAA
MAMMMXMMMM
MXMXAXMASX
";
#[test]
fn test1() {
assert_eq!(part1(TEST_INPUT), 18);
}
#[test]
fn test2() {
assert_eq!(part2(TEST_INPUT), 9);
}
}

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

126
src/day06.rs Normal file
View File

@@ -0,0 +1,126 @@
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: Grid<[bool; 5]> = Grid::from_default(m.content_width, m.content_height);
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
// this is our own little hash function to speed things up
if visited[pos][dir as usize % 5] {
return true;
}
visited[pos][dir as usize % 5] = true;
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);
}
}

109
src/day09.rs Normal file
View File

@@ -0,0 +1,109 @@
use std::{collections::BTreeMap, 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 free: BTreeMap<usize, usize> = BTreeMap::new();
// (start_index, len, file_id)
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() as usize;
if i % 2 == 0 {
files.push((head, l, i / 2));
} else {
free.insert(head, l);
}
head += l;
}
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);
}
}
}
files
.iter()
.map(|(start_index, l, file_id)| {
*file_id * (*start_index..start_index + l).sum::<RiddleResult>()
})
.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);
}
}

185
src/day12.rs Normal file
View File

@@ -0,0 +1,185 @@
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 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);
if next_c.is_none() || next_c.unwrap() != c {
} else {
further.push(next);
}
}
processed.insert(current);
}
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
BBCD
BBCC
EEEC
";
#[test]
fn test1() {
assert_eq!(part1(TEST_INPUT), 140);
}
#[test]
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);
}
}

190
src/day16.rs Normal file
View File

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

142
src/day17.rs Normal file
View File

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

147
src/day18.rs Normal file
View File

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

98
src/day19.rs Normal file
View File

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

299
src/day21.rs Normal file
View File

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

126
src/day22.rs Normal file
View File

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

150
src/day23.rs Normal file
View File

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

225
src/day24.rs Normal file
View File

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

117
src/day25.rs Normal file
View File

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

@@ -1,3 +1,26 @@
pub mod day01; pub mod day01;
pub mod day02; pub mod day02;
pub mod day03; 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;
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

@@ -1,23 +1,49 @@
use std::{collections::HashMap, env::args};
use advent_of_rust_2024::*; use advent_of_rust_2024::*;
use itertools::Itertools; use itertools::Itertools;
use std::time::Instant;
use std::{collections::HashMap, env::args};
fn main() { fn main() {
let mains: HashMap<u8, fn() -> ()> = HashMap::from_iter([ let mains: HashMap<u8, fn() -> ()> = HashMap::from_iter([
(1, day01::day_main as fn()), (1, day01::day_main as fn()),
(2, day02::day_main), (2, day02::day_main),
(3, day03::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),
(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 day: Option<u8> = args().nth(1).and_then(|a| a.parse().ok());
let Some(day) = day else { let Some(day) = day else {
let start = Instant::now();
mains mains
.iter() .iter()
.sorted_by_key(|entry| entry.0) .sorted_by_key(|entry| entry.0)
.for_each(|(d, f)| { .for_each(|(d, f)| {
println!("Day {d}:"); run(*d, f);
f();
}); });
let duration = start.elapsed();
println!();
println!("{COLOR}{ITALIC}All tasks took {duration:?}{RESET_FORMATTING}");
return; return;
}; };
@@ -30,6 +56,17 @@ fn main() {
return; return;
}; };
println!("Day {day}:"); run(day, f);
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";

35
src/template.rs Normal file
View File

@@ -0,0 +1,35 @@
use std::fs::read_to_string;
pub fn day_main() {
let input = read_to_string("input/day{{day}}.txt").unwrap();
let input = input.trim();
println!(" part1: {}", part1(input));
println!(" part2: {}", part2(input));
}
type RiddleResult = i64;
fn part1(input: &str) -> RiddleResult {
0
}
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(TEST_INPUT), 0);
}
#[test]
fn test2() {
assert_eq!(part2(TEST_INPUT), 0);
}
}

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

@@ -0,0 +1,263 @@
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 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 {
content_width: self.content_width,
content_height: self.content_height,
content: new_content,
}
}
}
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();
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,
}
}
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> {
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;