Compare commits

..
13 Commits
Author SHA1 Message Date
Jan-Bulthuis 0ff3b02db9 feat: Day 4 2025-12-04 09:20:37 +01:00
Jan-Bulthuis e3affe980a chore: Switched to WinnowDay 2025-12-03 23:16:00 +01:00
Jan-Bulthuis d08eabf619 fix: Allow dead code again but disallow unused 2025-12-03 23:10:28 +01:00
Jan-Bulthuis ff3fe411ae feat: Day 3 2025-12-03 23:05:13 +01:00
Jan-Bulthuis 22fc3511b7 feat: Fancier traits 2025-12-03 23:04:50 +01:00
Jan-Bulthuis 3740d93f81 feat: Day 2 2025-12-02 07:27:01 +01:00
Jan-Bulthuis 91d9d7b1dc feat: Day 1 2025-12-01 06:21:24 +01:00
Jan-Bulthuis f5788b2825 feat: Add flake 2025-12-01 06:20:31 +01:00
Jan-Bulthuis 2a340c2e04 day25 2024-12-25 06:26:15 +01:00
Jan-Bulthuis 561f762bc9 Removed unused import 2024-12-25 06:26:11 +01:00
Jan-Bulthuis 6585356f0e day24 2024-12-25 05:53:45 +01:00
Jan-Bulthuis ac4c0f3838 day23 2024-12-24 15:20:16 +01:00
Jan-Bulthuis b49467a59e Fuck it we ball 2024-12-22 20:09:58 +01:00
17 changed files with 1575 additions and 14 deletions

No files matched your search

+2 -1
View File
@@ -1,3 +1,4 @@
*/target/ */target/
*/input/ */input/
*.out *.out
.direnv
+9 -11
View File
@@ -131,11 +131,9 @@ impl NumButton {
} }
} }
type Input = String;
#[aoc_generator(day21)] #[aoc_generator(day21)]
fn parse(input: &str) -> Input { fn parse(input: &str) -> &'static str {
input.to_string() unsafe { std::mem::transmute(input) }
} }
type Path = [DistanceSize; 6]; type Path = [DistanceSize; 6];
@@ -336,7 +334,7 @@ const CHAR_IDX: [usize; 10] = [
]; ];
#[aoc(day21, part1)] #[aoc(day21, part1)]
fn part1(input: &Input) -> DistanceSize { fn part1(input: &str) -> DistanceSize {
let num_paths = const { let num_paths = const {
let steps = precompute_steps_new::<2>([[1; 5]; 5]); let steps = precompute_steps_new::<2>([[1; 5]; 5]);
let paths = precompute_paths(); let paths = precompute_paths();
@@ -358,7 +356,7 @@ fn part1(input: &Input) -> DistanceSize {
} }
#[aoc(day21, part2)] #[aoc(day21, part2)]
fn part2(input: &Input) -> DistanceSize { fn part2(input: &str) -> DistanceSize {
let num_paths = const { let num_paths = const {
let steps = precompute_steps_new::<25>([[1; 5]; 5]); let steps = precompute_steps_new::<25>([[1; 5]; 5]);
let paths = precompute_paths(); let paths = precompute_paths();
@@ -385,10 +383,10 @@ mod tests {
#[test] #[test]
fn part1_example() { fn part1_example() {
assert_eq!(part1(&parse("379A")), 64 * 379); assert_eq!(part1(parse("379A")), 64 * 379);
assert_eq!(part1(&parse("179A")), 68 * 179); assert_eq!(part1(parse("179A")), 68 * 179);
assert_eq!(part1(&parse("456A")), 64 * 456); assert_eq!(part1(parse("456A")), 64 * 456);
assert_eq!(part1(&parse("980A")), 60 * 980); assert_eq!(part1(parse("980A")), 60 * 980);
assert_eq!(part1(&parse("029A")), 68 * 29); assert_eq!(part1(parse("029A")), 68 * 29);
} }
} }
+233
View File
@@ -0,0 +1,233 @@
use aoc_runner_derive::{aoc, aoc_generator};
use hashbrown::{HashMap, HashSet};
type Input = (usize, [Vec<usize>; 26 * 26], HashMap<usize, String>);
#[aoc_generator(day23)]
fn parse(input: &str) -> Input {
let mut i = 0;
let mut names = HashMap::new();
let mut ids = HashMap::new();
let mut adj_list = [const { Vec::new() }; 26 * 26];
input.lines().for_each(|line| {
let mut splits = line.split('-');
let left = splits.next().unwrap().to_string();
let right = splits.next().unwrap().to_string();
let left_id = {
*ids.entry(left.clone()).or_insert_with(|| {
let id = i;
i += 1;
names.insert(id, left);
id
})
};
let right_id = {
*ids.entry(right.clone()).or_insert_with(|| {
let id = i;
i += 1;
names.insert(id, right);
id
})
};
adj_list[left_id].push(right_id);
adj_list[right_id].push(left_id);
});
(i, adj_list, names)
}
#[aoc(day23, part1)]
fn part1(input: &Input) -> usize {
let num = input.0;
let adj_list = &input.1;
let names = &input.2;
(0..num)
.filter(|id| names[id].starts_with("t"))
.flat_map(|id| {
let mut three_groups = HashSet::new();
let adj = &adj_list[id];
for left in 0..adj.len() {
for right in left + 1..adj.len() {
if adj_list[adj[left]].contains(&adj[right]) {
let mut group = [id, adj[left], adj[right]];
group.sort();
three_groups.insert((group[0], group[1], group[2]));
}
}
}
three_groups
})
.collect::<HashSet<(usize, usize, usize)>>()
.into_iter()
.count()
}
#[aoc(day23, part2)]
fn part2(input: &Input) -> String {
let num = input.0;
let adj_list = &input.1;
let names = &input.2;
let max_clique = (0..num)
.filter(|id| names[id].starts_with("t"))
.flat_map(|id| {
let mut three_groups = HashSet::new();
let adj = &adj_list[id];
for left in 0..adj.len() {
for right in left + 1..adj.len() {
if adj_list[adj[left]].contains(&adj[right]) {
let mut group = [id, adj[left], adj[right]];
group.sort();
three_groups.insert((group[0], group[1], group[2]));
}
}
}
three_groups
})
.collect::<HashSet<(usize, usize, usize)>>()
.into_iter()
.flat_map(|(a, b, c)| {
let clique = vec![a, b, c];
expand_cliques(clique, num, adj_list)
})
.max_by_key(|clique| clique.len())
.unwrap();
let mut names = max_clique
.iter()
.map(|id| names[id].clone())
.collect::<Vec<String>>();
names.sort();
names.join(",")
}
fn expand_cliques(current: Vec<usize>, num: usize, adj: &[Vec<usize>]) -> Vec<Vec<usize>> {
let mut expansions: Vec<Vec<usize>> = vec![current.clone()];
for node in 0..num {
if current.contains(&node) {
continue;
}
if !current
.iter()
.all(|clique_node| adj[*clique_node].contains(&node))
{
continue;
}
let mut pushed = false;
for clique in &mut expansions {
if clique
.iter()
.all(|clique_node| adj[*clique_node].contains(&node))
{
clique.push(node);
pushed = true;
continue;
}
}
if !pushed {
let mut new_clique = current.clone();
new_clique.push(node);
expansions.push(new_clique);
}
}
expansions
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn part1_example() {
assert_eq!(
part1(&parse(
"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"
)),
7
);
}
#[test]
fn part2_example() {
assert_eq!(
part2(&parse(
"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"
)),
"co,de,ka,ta"
);
}
}
+303
View File
@@ -0,0 +1,303 @@
use std::collections::VecDeque;
use aoc_runner_derive::{aoc, aoc_generator};
use hashbrown::HashMap;
use nom::{
bytes::complete::tag,
character::complete::{anychar, newline, one_of, space1, u64},
multi::{fill, many1, separated_list0},
sequence::{delimited, separated_pair},
IResult,
};
type Line = [char; 3];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Operation {
And,
Or,
Xor,
}
#[derive(Debug, Clone, Copy)]
struct Gate {
operation: Operation,
in_0: Line,
in_1: Line,
out: Line,
}
type Input = (Vec<(Line, u64)>, Vec<Gate>);
#[aoc_generator(day24)]
fn parse(input: &str) -> Input {
separated_pair(
separated_list0(newline, separated_pair(parse_line, tag(": "), u64)),
tag("\n\n"),
separated_list0(newline, parse_instruction),
)(input)
.unwrap()
.1
}
fn parse_line(input: &str) -> IResult<&str, [char; 3]> {
let mut buffer = ['0'; 3];
let (input, _) = fill(anychar, &mut buffer)(input)?;
Ok((input, buffer))
}
fn parse_instruction(input: &str) -> IResult<&str, Gate> {
let (input, in_0) = parse_line(input)?;
let (input, operation) = delimited(space1, many1(one_of("ANDXOR")), space1)(input)?;
let (input, in_1) = parse_line(input)?;
let (input, _) = tag(" -> ")(input)?;
let (input, out) = parse_line(input)?;
match operation[0] {
'A' => Ok((
input,
Gate {
in_0,
in_1,
out,
operation: Operation::And,
},
)),
'O' => Ok((
input,
Gate {
in_0,
in_1,
out,
operation: Operation::Or,
},
)),
'X' => Ok((
input,
Gate {
in_0,
in_1,
out,
operation: Operation::Xor,
},
)),
_ => unreachable!(),
}
}
#[aoc(day24, part1)]
fn part1(input: &Input) -> usize {
let fixed = &input.0;
let mut values = HashMap::new();
for (line, value) in fixed {
values.insert(line, *value);
}
let mut gates = VecDeque::new();
for gate in &input.1 {
gates.push_back(gate);
}
while let Some(gate) = gates.pop_front() {
if values.contains_key(&gate.in_0) && values.contains_key(&gate.in_1) {
let in_0 = values[&gate.in_0];
let in_1 = values[&gate.in_1];
let out = match gate.operation {
Operation::And => in_0 & in_1,
Operation::Or => in_0 | in_1,
Operation::Xor => in_0 ^ in_1,
};
values.insert(&gate.out, out);
} else {
gates.push_back(gate);
}
}
values
.into_iter()
.filter(|(line, value)| line[0] == 'z' && *value == 1)
.map(|(line, _)| {
1 << line[1..3]
.iter()
.collect::<String>()
.parse::<u64>()
.unwrap()
})
.sum()
}
#[aoc(day24, part2)]
fn part2(input: &Input) -> String {
let swaps: &[(Line, Line)] = &[
(['h', 'm', 't'], ['z', '1', '8']),
(['b', 'f', 'q'], ['z', '2', '7']),
(['h', 'k', 'h'], ['z', '3', '1']),
(['f', 'j', 'p'], ['b', 'n', 'g']),
];
// let swaps: &[(Line, Line)] = &[];
let mut gates = input.1.clone();
for gate in &mut gates {
for (from, to) in swaps {
if gate.out == *from {
gate.out = *to;
} else if gate.out == *to {
gate.out = *from;
}
}
}
for gate in &gates {
if gate.out[0] == 'z' && gate.operation != Operation::Xor {
println!("gate {:?} outputs to a z but is not xor", gate);
}
}
let mut c = ['r', 'j', 'r'];
for bit in 1..=44 {
let x = [
'x',
(bit as u8 / 10 + 48) as char,
(bit as u8 % 10 + 48) as char,
];
let y = [
'y',
(bit as u8 / 10 + 48) as char,
(bit as u8 % 10 + 48) as char,
];
let xy_gates = find_gate(&gates, &x, &y);
assert_eq!(
xy_gates.len(),
2,
"there is not exactly two xy gates {:?}\nrelated gates: {:?}",
xy_gates,
find_debug_gate(&gates, &x, &y)
);
let line_xy_xor = xy_gates
.iter()
.find(|g| g.operation == Operation::Xor)
.unwrap()
.out;
let line_xy_and = xy_gates
.iter()
.find(|g| g.operation == Operation::And)
.unwrap()
.out;
let xyc_gates = find_gate(&gates, &line_xy_xor, &c);
assert_eq!(xyc_gates.len(), 2,
"there is not exactly two output gates {:?}\nrelated gates: {:?}\nxy_and: {}\nxy_xor: {}",
xyc_gates,
find_debug_gate(&gates, &line_xy_xor, &c),
display_line(&line_xy_and),
display_line(&line_xy_xor),
);
let line_xyc_xor = xyc_gates
.iter()
.find(|g| g.operation == Operation::Xor)
.unwrap()
.out;
let line_xyc_and = xyc_gates
.iter()
.find(|g| g.operation == Operation::And)
.unwrap()
.out;
let xyco_gates = find_gate(&gates, &line_xyc_and, &line_xy_and);
assert_eq!(
xyco_gates.len(),
1,
"there is no or more than one output gate {:?}\nrelated gates: {:?}\nxy_and: {}\nxy_xor: {}\nxyc_and: {}\nxyc_xor: {}",
xyco_gates,
find_debug_gate(&gates, &line_xyc_and, &line_xy_and),
display_line(&line_xy_and),
display_line(&line_xy_xor),
display_line(&line_xyc_and),
display_line(&line_xyc_xor),
);
c = xyco_gates[0].out;
println!(
"for bit {} z-output is {} and carry out is {}",
bit,
display_line(&line_xyc_xor),
display_line(&c)
);
}
let mut wires = swaps
.iter()
.flat_map(|(a, b)| [display_line(a), display_line(b)])
.collect::<Vec<String>>();
wires.sort();
wires.join(",")
}
fn display_line(line: &Line) -> String {
line.iter().collect()
}
fn find_gate(gates: &[Gate], in_0: &Line, in_1: &Line) -> Vec<Gate> {
gates
.iter()
.filter(|gate| {
(gate.in_0 == *in_0 && gate.in_1 == *in_1) || (gate.in_0 == *in_1 && gate.in_1 == *in_0)
})
.copied()
.collect()
}
fn find_debug_gate(gates: &[Gate], in_0: &Line, in_1: &Line) -> Vec<Gate> {
gates
.iter()
.filter(|gate| {
gate.in_0 == *in_0 || gate.in_1 == *in_1 || gate.in_0 == *in_1 || gate.in_1 == *in_0
})
.copied()
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn part1_example() {
assert_eq!(
part1(&parse(
"x00: 1
x01: 1
x02: 1
y00: 0
y01: 1
y02: 0
x00 AND y00 -> z00
x01 XOR y01 -> z01
x02 OR y02 -> z02"
)),
4
);
}
// #[test]
// fn part2_example() {
// assert_eq!(
// part2(&parse(include_str!("../input/2024/day24.txt").trim_end())),
// "z00,z01,z02,z05"
// );
// }
}
+152
View File
@@ -0,0 +1,152 @@
use aoc_runner_derive::{aoc, aoc_generator};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Cell {
Empty,
Filled,
}
type Code = [usize; 5];
type Input = (Vec<Code>, Vec<Code>);
#[aoc_generator(day25)]
fn parse(input: &str) -> Input {
let (keys, locks): (Vec<Option<Vec<Vec<Cell>>>>, Vec<Option<Vec<Vec<Cell>>>>) = input
.split("\n\n")
.map(|block| {
block
.lines()
.map(|line| {
line.chars()
.map(|c| match c {
'.' => Cell::Empty,
'#' => Cell::Filled,
_ => panic!("Invalid cell"),
})
.collect()
})
.collect()
})
.map(|block: Vec<Vec<Cell>>| {
if block[0][0] == Cell::Filled {
(None, Some(block))
} else {
(Some(block), None)
}
})
.unzip();
let keys = keys
.into_iter()
.flatten()
.map(|block| {
let mut buffer = [0; 5];
for (y, row) in block.iter().enumerate() {
for x in 0..5 {
if row[x] == Cell::Empty {
buffer[x] = y;
}
}
}
buffer
})
.collect();
let locks = locks
.into_iter()
.flatten()
.map(|block| {
let mut buffer = [0; 5];
for (y, row) in block.iter().enumerate() {
for x in 0..5 {
if row[x] == Cell::Filled {
buffer[x] = y;
}
}
}
buffer
})
.collect();
(keys, locks)
}
#[aoc(day25, part1)]
fn part1(input: &Input) -> usize {
let (keys, locks) = input;
let mut valid_combinations = 0;
for key in keys {
for lock in locks {
if (0..5).all(|i| key[i] >= lock[i]) {
valid_combinations += 1;
}
}
}
valid_combinations
}
// #[aoc(day25, part2)]
// fn part2(input: &Input) -> usize {
// todo!()
// }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn part1_example() {
assert_eq!(
part1(&parse(
"#####
.####
.####
.####
.#.#.
.#...
.....
#####
##.##
.#.##
...##
...#.
...#.
.....
.....
#....
#....
#...#
#.#.#
#.###
#####
.....
.....
#.#..
###..
###.#
###.#
#####
.....
.....
.....
#....
#.#..
#.#.#
#####"
)),
3
);
}
// #[test]
// fn part2_example() {
// assert_eq!(part2(&parse("<EXAMPLE>")), 0);
// }
}
+5 -2
View File
@@ -1,5 +1,3 @@
mod day22;
mod day21;
mod day1; mod day1;
mod day10; mod day10;
mod day11; mod day11;
@@ -13,6 +11,11 @@ mod day18;
mod day19; mod day19;
mod day2; mod day2;
mod day20; mod day20;
mod day21;
mod day22;
mod day23;
mod day24;
mod day25;
mod day3; mod day3;
mod day4; mod day4;
mod day5; mod day5;
+149
View File
@@ -0,0 +1,149 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "allocator-api2"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "aoc_2025"
version = "0.1.0"
dependencies = [
"hashbrown",
"num",
"num-modular",
"topological-sort",
"winnow",
]
[[package]]
name = "autocfg"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "hashbrown"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
]
[[package]]
name = "memchr"
version = "2.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"
[[package]]
name = "num"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
dependencies = [
"num-bigint",
"num-complex",
"num-integer",
"num-iter",
"num-rational",
"num-traits",
]
[[package]]
name = "num-bigint"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-complex"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
dependencies = [
"num-traits",
]
[[package]]
name = "num-integer"
version = "0.1.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
dependencies = [
"num-traits",
]
[[package]]
name = "num-iter"
version = "0.1.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf"
dependencies = [
"autocfg",
"num-integer",
"num-traits",
]
[[package]]
name = "num-modular"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17bb261bf36fa7d83f4c294f834e91256769097b3cb505d44831e0a179ac647f"
[[package]]
name = "num-rational"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
dependencies = [
"num-bigint",
"num-integer",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "topological-sort"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea68304e134ecd095ac6c3574494fc62b909f416c4fca77e440530221e549d3d"
[[package]]
name = "winnow"
version = "0.7.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829"
dependencies = [
"memchr",
]
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "aoc_2025"
version = "0.1.0"
edition = "2024"
[dependencies]
hashbrown = "0.16.1"
num = "0.4.3"
num-modular = "0.6.1"
topological-sort = "0.2.2"
winnow = "0.7.14"
+3
View File
@@ -0,0 +1,3 @@
```bash
bacon test -- dayN
```
+124
View File
@@ -0,0 +1,124 @@
use crate::{AoC, WinnowDay};
use winnow::{
Parser, Result,
ascii::{digit1, multispace0},
combinator::{alt, preceded, repeat},
};
type Parsed = Vec<Side>;
enum Side {
Left(i64),
Right(i64),
}
fn day() -> impl WinnowDay {
AoC::new(parse as _, part1 as _, part2 as _)
}
fn parse(input: &mut &str) -> Result<Parsed> {
repeat(1.., parse_line).parse_next(input)
}
fn parse_line(input: &mut &str) -> Result<Side> {
preceded(multispace0, alt((parse_left, parse_right))).parse_next(input)
}
fn parse_left(input: &mut &str) -> Result<Side> {
preceded("L", digit1.parse_to())
.map(Side::Left)
.parse_next(input)
}
fn parse_right(input: &mut &str) -> Result<Side> {
preceded("R", digit1.parse_to())
.map(Side::Right)
.parse_next(input)
}
fn part1(input: Parsed) -> String {
let mut res = 0;
let mut pos = 50i64;
for change in input {
match change {
Side::Left(dx) => pos = (pos + 100 - dx) % 100,
Side::Right(dx) => pos = (pos + dx) % 100,
}
if pos == 0 {
res += 1
}
}
format!("{res}")
}
fn part2(input: Parsed) -> String {
let input = input
.iter()
.flat_map(|side| match side {
Side::Left(dx) => (0..*dx).map(|_| Side::Left(1)).collect::<Vec<Side>>(),
Side::Right(dx) => (0..*dx).map(|_| Side::Right(1)).collect::<Vec<Side>>(),
})
.collect::<Vec<Side>>();
let mut res = 0;
let mut pos = 50i64;
for change in input {
match change {
Side::Left(dx) => pos = (pos + 100 - dx) % 100,
Side::Right(dx) => pos = (pos + dx) % 100,
}
if pos == 0 {
res += 1
}
}
format!("{res}")
}
#[cfg(test)]
mod tests {
use crate::Day;
use super::*;
#[test]
fn part1_test() {
day().assert1(
"L68
L30
R48
L5
R60
L55
L1
L99
R14
L82",
"3",
);
}
#[test]
fn part1_solve() {
day().assert1(include_str!("../input/day1.txt"), "982");
}
#[test]
fn part2_test() {
day().assert2(
"L68
L30
R48
L5
R60
L55
L1
L99
R14
L82",
"6",
);
}
#[test]
fn part2_solve() {
day().assert2(include_str!("../input/day1.txt"), "6106");
}
}
+87
View File
@@ -0,0 +1,87 @@
use crate::{AoC, WinnowDay};
use winnow::{
Parser, Result,
ascii::digit1,
combinator::{separated, separated_pair},
};
type Parsed = Vec<(u64, u64)>;
fn day() -> impl WinnowDay {
AoC::new(parse as _, part1 as _, part2 as _)
}
fn parse(input: &mut &str) -> Result<Parsed> {
separated(1.., parse_range, ",").parse_next(input)
}
fn parse_range(input: &mut &str) -> Result<(u64, u64)> {
separated_pair(digit1.parse_to(), "-", digit1.parse_to()).parse_next(input)
}
fn part1(input: Parsed) -> String {
let res = input
.iter()
.map(|(from, to)| {
(*from..=*to)
.filter(|i| {
let n = (i.ilog10() + 1) >> 1;
let p = 10u64.pow(n);
i / p == i % p
})
.sum::<u64>()
})
.sum::<u64>();
format!("{res}")
}
fn part2(input: Parsed) -> String {
let res = input
.iter()
.map(|(from, to)| {
(*from..=*to)
.filter(|i| {
let n = i.ilog10() + 1;
(1..=(n >> 1)).filter(|p| n % p == 0).any(|p| {
(1..(n / p))
.all(|s| i % 10u64.pow(p) == (i / 10u64.pow(p * s)) % 10u64.pow(p))
})
})
.sum::<u64>()
})
.sum::<u64>();
format!("{res}")
}
#[cfg(test)]
mod tests {
use crate::Day;
use super::*;
#[test]
fn part1_test() {
day().assert1(
"11-22,95-115,998-1012,1188511880-1188511890,222220-222224,1698522-1698528,446443-446449,38593856-38593862,565653-565659,824824821-824824827,2121212118-2121212124",
"1227775554",
);
}
#[test]
fn part1_solve() {
day().assert1(include_str!("../input/day2.txt"), "12599655151");
}
#[test]
fn part2_test() {
day().assert2(
"11-22,95-115,998-1012,1188511880-1188511890,222220-222224,1698522-1698528,446443-446449,38593856-38593862,565653-565659,824824821-824824827,2121212118-2121212124",
"4174379265",
);
}
#[test]
fn part2_solve() {
day().assert2(include_str!("../input/day2.txt"), "20942028255");
}
}
+102
View File
@@ -0,0 +1,102 @@
use std::iter::Sum;
use crate::{AoC, WinnowDay};
use winnow::{
Parser, Result,
ascii::newline,
combinator::{repeat, terminated},
error::ContextError,
token::one_of,
};
fn day() -> impl WinnowDay {
AoC::new(parse as _, part1 as _, part2 as _)
}
fn parse(input: &mut &str) -> Result<Vec<Vec<usize>>> {
repeat(1.., parse_line).parse_next(input)
}
fn parse_line(input: &mut &str) -> Result<Vec<usize>, ContextError> {
terminated(
repeat(
1..,
one_of(('0'..='9',)).map(|c: char| c.to_string().parse::<usize>().unwrap()),
),
newline,
)
.parse_next(input)
}
fn part1(input: Vec<Vec<usize>>) -> usize {
input.iter().map(joltage(2)).sum()
}
fn part2(input: Vec<Vec<usize>>) -> usize {
input.iter().map(joltage(12)).sum()
}
fn joltage<
'a,
B: IntoIterator<IntoIter = I> + Copy,
I: ExactSizeIterator<Item = &'a N>,
N: Sum<&'a N> + Into<usize> + From<usize> + Copy + Default + 'a,
>(
size: usize,
) -> impl Fn(B) -> N {
move |line| {
(line.into_iter().len() - size..line.into_iter().len())
.fold((0, 0), |(start, val), end| {
line.into_iter()
.enumerate()
.skip(start)
.take(end - start + 1)
.map(|(i, v)| (i + 1, (*v).into() + val * 10))
.reduce(|a, b| if a.1 >= b.1 { a } else { b })
.unwrap()
})
.1
.into()
}
}
#[cfg(test)]
mod tests {
use crate::Day;
use super::*;
#[test]
fn part1_test() {
day().assert1(
"987654321111111
811111111111119
234234234234278
818181911112111
",
"357",
);
}
#[test]
fn part1_solve() {
day().assert1(include_str!("../input/day3.txt"), "17343");
}
#[test]
fn part2_test() {
day().assert2(
"987654321111111
811111111111119
234234234234278
818181911112111
",
"3121910778619",
);
}
#[test]
fn part2_solve() {
day().assert2(include_str!("../input/day3.txt"), "172664333119298");
}
}
+155
View File
@@ -0,0 +1,155 @@
use winnow::{
Parser, Result,
ascii::{multispace0, newline},
combinator::{alt, preceded, repeat, terminated},
};
use crate::{AoC, SimpleDay, WinnowDay};
fn day() -> impl WinnowDay {
AoC::new(parse as _, part1 as _, part2 as _)
}
type Parsed = Vec<Vec<Cell>>;
#[derive(Debug, PartialEq, Eq)]
enum Cell {
Empty,
Paper,
}
impl Cell {
fn is_empty(&self) -> bool {
self == &Cell::Empty
}
fn is_paper(&self) -> bool {
self == &Cell::Paper
}
}
fn parse(input: &mut &str) -> Result<Parsed> {
repeat(1.., preceded(multispace0, parse_line)).parse_next(input)
}
fn parse_line(input: &mut &str) -> Result<Vec<Cell>> {
repeat(1.., parse_cell).parse_next(input)
}
fn parse_cell(input: &mut &str) -> Result<Cell> {
alt((".".map(|_| Cell::Empty), "@".map(|_| Cell::Paper))).parse_next(input)
}
fn part1(input: Parsed) -> usize {
let mut input = input;
remove_paper(&mut input)
}
fn remove_paper(input: &mut [Vec<Cell>]) -> usize {
let mut score = 0;
let mut access = Vec::new();
let h = input.len();
let w = input[0].len();
let directions = [
(-1, -1),
(0, -1),
(1, -1),
(1, 0),
(1, 1),
(0, 1),
(-1, 1),
(-1, 0),
];
for y in 0..h {
for x in 0..w {
match input[y][x] {
Cell::Empty => {}
Cell::Paper => {
let count = directions
.iter()
.filter(|dir| {
let nx = x as isize + dir.0;
let ny = y as isize + dir.1;
nx >= 0
&& nx < w as isize
&& ny >= 0
&& ny < h as isize
&& input[ny as usize][nx as usize].is_paper()
})
.count();
if count < 4 {
score += 1;
access.push((x, y));
}
}
}
}
}
access.iter().for_each(|(x, y)| {
input[*y][*x] = Cell::Empty;
});
score
}
fn part2(input: Parsed) -> usize {
let mut input = input;
let mut score = 0;
loop {
let removed = remove_paper(&mut input);
score += removed;
if removed == 0 {
return score;
}
}
}
#[cfg(test)]
mod tests {
use crate::Day;
use super::*;
#[test]
fn part1_test() {
day().assert1(
"..@@.@@@@.
@@@.@.@.@@
@@@@@.@.@@
@.@@@@..@.
@@.@@@@.@@
.@@@@@@@.@
.@.@.@.@@@
@.@@@.@@@@
.@@@@@@@@.
@.@.@@@.@.",
"13",
);
}
#[test]
fn part1_solve() {
day().assert1(include_str!("../input/day4.txt"), "1356");
}
#[test]
fn part2_test() {
day().assert2(
"..@@.@@@@.
@@@.@.@.@@
@@@@@.@.@@
@.@@@@..@.
@@.@@@@.@@
.@@@@@@@.@
.@.@.@.@@@
@.@@@.@@@@
.@@@@@@@@.
@.@.@@@.@.",
"43",
);
}
#[test]
fn part2_solve() {
day().assert2(include_str!("../input/day4.txt"), "8713");
}
}
+99
View File
@@ -0,0 +1,99 @@
#![allow(dead_code)]
#![allow(unused)]
use std::fmt::{Debug, Display};
use winnow::Parser;
mod day1;
mod day2;
mod day3;
mod day4;
trait Day {
fn assert1(&self, input: &str, output: &str);
fn assert2(&self, input: &str, output: &str);
}
struct AoC<P, O1, O2> {
parse: P,
part1: O1,
part2: O2,
}
impl<P, O1, O2> AoC<P, O1, O2> {
fn new(parse: P, part1: O1, part2: O2) -> Self {
Self {
parse,
part1,
part2,
}
}
}
trait SimpleDay: Day {}
impl<P, O1, O2> SimpleDay for AoC<fn(String) -> P, fn(P) -> O1, fn(P) -> O2>
where
O1: Display,
O2: Display,
{
}
impl<P, O1, O2> Day for AoC<fn(String) -> P, fn(P) -> O1, fn(P) -> O2>
where
O1: Display,
O2: Display,
{
fn assert1(&self, input: &str, output: &str) {
let parsed = (self.parse)(input.to_string());
assert_eq!(format!("{}", (self.part1)(parsed)), output);
}
fn assert2(&self, input: &str, output: &str) {
let parsed = (self.parse)(input.to_string());
assert_eq!(format!("{}", (self.part2)(parsed)), output);
}
}
trait WinnowDay: Day {}
impl<O, E, O1, O2> WinnowDay
for AoC<for<'a, 'b> fn(&'a mut &'b str) -> Result<O, E>, fn(O) -> O1, fn(O) -> O2>
where
E: Debug,
O1: Display,
O2: Display,
{
}
fn as_parser<O, E>(
func: for<'a, 'b> fn(&'a mut &'b str) -> Result<O, E>,
) -> impl for<'a> Parser<&'a str, O, E>
where
E: Debug,
{
func
}
impl<O, E, O1, O2> Day
for AoC<for<'a, 'b> fn(&'a mut &'b str) -> Result<O, E>, fn(O) -> O1, fn(O) -> O2>
where
E: Debug,
O1: Display,
O2: Display,
{
fn assert1(&self, input: &str, output: &str) {
let mut input = input;
let mut parser = as_parser(self.parse);
let parsed = parser.parse_next(&mut input).unwrap();
assert_eq!(format!("{}", (self.part1)(parsed)), output);
}
fn assert2(&self, input: &str, output: &str) {
let mut input = input;
let mut parser = as_parser(self.parse);
let parsed = parser.parse_next(&mut input).unwrap();
assert_eq!(format!("{}", (self.part2)(parsed)), output);
}
}
+48
View File
@@ -0,0 +1,48 @@
use winnow::{Parser, Result};
use crate::{AoC, SimpleDay, WinnowDay};
fn day() -> impl WinnowDay {
AoC::new(parse as _, part1 as _, part2 as _)
}
type Parsed = ();
fn parse(input: &mut &str) -> Result<Parsed> {
"".map(|_| ()).parse_next(input)
}
fn part1(input: Parsed) -> usize {
0
}
fn part2(input: Parsed) -> usize {
0
}
#[cfg(test)]
mod tests {
use crate::Day;
use super::*;
#[test]
fn part1_test() {
day().assert1("", "");
}
#[test]
fn part1_solve() {
day().assert1(include_str!("../input/day.txt"), "");
}
// #[test]
// fn part2_test() {
// day().assert2("", "");
// }
// #[test]
// fn part2_solve() {
// day().assert2(include_str!("../input/day.txt"), "");
// }
}
Generated
+61
View File
@@ -0,0 +1,61 @@
{
"nodes": {
"flake-utils": {
"inputs": {
"systems": "systems"
},
"locked": {
"lastModified": 1731533236,
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1764242076,
"narHash": "sha256-sKoIWfnijJ0+9e4wRvIgm/HgE27bzwQxcEmo2J/gNpI=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "2fad6eac6077f03fe109c4d4eb171cf96791faa4",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
}
},
"systems": {
"locked": {
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}
},
"root": "root",
"version": 7
}
+32
View File
@@ -0,0 +1,32 @@
{
inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
flake-utils.url = "github:numtide/flake-utils";
};
outputs =
{
nixpkgs,
flake-utils,
...
}:
flake-utils.lib.eachDefaultSystem (
system:
let
pkgs = import nixpkgs {
inherit system;
};
in
{
devShells.default = pkgs.mkShell {
buildInputs = with pkgs; [
cargo
rustc
rustfmt
clippy
bacon
];
};
}
);
}