convert to aoc-runner and day1 solutions

This commit is contained in:
2025-12-01 13:59:01 -08:00
parent 3a3c3c9ab6
commit 331755f1cf
12 changed files with 883 additions and 200 deletions

60
src/day1.rs Normal file
View File

@@ -0,0 +1,60 @@
use aoc_runner_derive::{aoc, aoc_generator};
use itertools::Itertools;
use std::io::BufRead;
#[aoc_generator(day1)]
// Sum the calories of each elf's food items
fn parse(input: &[u8]) -> Vec<u64> {
let mut result = Vec::new();
let mut cur_elf = 0u64;
for line in input.lines() {
if let Ok(calories) = line.unwrap().parse::<u64>() {
cur_elf += calories
} else {
result.push(cur_elf);
cur_elf = 0
}
}
result.push(cur_elf);
result
}
#[aoc(day1, part1)]
fn part1(input: &Vec<u64>) -> u64 {
*input.iter().max().unwrap()
}
#[aoc(day1, part2)]
fn part2(input: &Vec<u64>) -> u64 {
input.iter().sorted().rev().take(3).sum::<u64>()
}
#[cfg(test)]
mod tests {
use super::*;
const EXAMPLE: &[u8] = b"1000
2000
3000
4000
5000
6000
7000
8000
9000
10000";
#[test]
fn part1_example() {
assert_eq!(part1(&parse(EXAMPLE)), 24000);
}
#[test]
fn part2_example() {
assert_eq!(part2(&parse(EXAMPLE)), 45000);
}
}

74
src/day6.rs Normal file
View File

@@ -0,0 +1,74 @@
use aoc_runner_derive::aoc;
use itertools::Itertools;
use std::io::BufRead;
// PROBLEM 1 solution
#[aoc(day6, part1)]
fn part1(input: &[u8]) -> u64 {
let s = input.lines().next().unwrap().unwrap();
s.as_bytes()
.windows(4)
.enumerate()
.find_map(|(i, window)| {
if window[1..4].iter().all(|c| *c != window[0])
&& window[2..4].iter().all(|c| *c != window[1])
&& window[2] != window[3]
{
println!(
"Unique window: {:?} at {}",
window.iter().map(|c| *c as char).collect_vec(),
i
);
Some(i + 4)
} else {
None
}
})
.unwrap() as u64
}
// PROBLEM 2 solution
#[aoc(day6, part2)]
fn part2(input: &[u8]) -> u64 {
let s = input.lines().next().unwrap().unwrap();
let size = 14;
s.as_bytes()
.windows(size)
.enumerate()
.find_map(|(i, window)| {
for i in 1..size {
let shifted = &window[i..];
if shifted.iter().enumerate().any(|(j, c)| *c == window[j]) {
return None;
}
}
return Some(i + 14);
})
.unwrap() as u64
}
#[cfg(test)]
mod tests {
use crate::day6::*;
const EXAMPLE1: &[u8] = b"bvwbjplbgvbhsrlpgdmjqwftvncz";
const EXAMPLE2: &[u8] = b"nppdvjthqldpwncqszvftbrmjlhg";
const EXAMPLE3: &[u8] = b"nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg";
const EXAMPLE4: &[u8] = b"zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw";
#[test]
fn problem1_example() {
assert_eq!(part1(EXAMPLE1), 5);
assert_eq!(part1(EXAMPLE2), 6);
assert_eq!(part1(EXAMPLE3), 10);
assert_eq!(part1(EXAMPLE4), 11);
}
#[test]
fn problem2_example() {
assert_eq!(part2(EXAMPLE1), 23);
assert_eq!(part2(EXAMPLE2), 23);
assert_eq!(part2(EXAMPLE3), 29);
assert_eq!(part2(EXAMPLE4), 26);
}
}

6
src/lib.rs Normal file
View File

@@ -0,0 +1,6 @@
mod day1;
use aoc_runner_derive::aoc_lib;
pub mod day6;
aoc_lib! { year = 2022 }

3
src/main.rs Normal file
View File

@@ -0,0 +1,3 @@
use aoc_runner_derive::aoc_main;
aoc_main! { lib = aoc2022 }