diff --git a/.aoc_tiles/tiles/2026/02.png b/.aoc_tiles/tiles/2026/02.png new file mode 100644 index 0000000..1d73bd4 Binary files /dev/null and b/.aoc_tiles/tiles/2026/02.png differ diff --git a/README.md b/README.md index 07ef47a..9d1d289 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,11 @@

- 2026 - 2 ⭐ - Rust + 2026 - 4 ⭐ - Rust

+ + + diff --git a/src/day2.rs b/src/day2.rs new file mode 100644 index 0000000..34ffa0c --- /dev/null +++ b/src/day2.rs @@ -0,0 +1,89 @@ +use aoc_runner_derive::{aoc, aoc_generator}; +use itertools::Itertools; +// #[aoc_generator(day2)] +// fn parse(input: &str) -> { +// todo!() +// } + +const SEQUENCE: &[u8] = b"roygbv"; + +// The distance required to move forward from start to end +fn move_distance(start: u8, end: u8) -> i64 { + let mut distance = end as i64 - (start as i64 % SEQUENCE.len() as i64); + if distance <= 0 { + distance += SEQUENCE.len() as i64 + }; + distance +} + +#[aoc(day2, part1)] +fn part1(input: &str) -> u64 { + let instructions = input.as_bytes(); + let mut cur_pos = 0i64; + + for i in instructions { + let next_pos = SEQUENCE.iter().position(|c| c == i).unwrap() as u8; + cur_pos += move_distance((cur_pos % SEQUENCE.len() as i64) as u8, next_pos); + } + + cur_pos as u64 +} + +#[aoc(day2, part2)] +fn part2(input: &str) -> u64 { + let mut instructions = input + .as_bytes() + .iter() + .map(|i| SEQUENCE.iter().position(|c| c == i).unwrap() as u8) + .collect_vec(); + + // bring like instructions together, but this will minimize the distance between blocks + instructions.sort_unstable(); + let mut chunks = instructions.chunk_by(|a, b| a == b).collect_vec(); + let mut final_chunks = Vec::new(); + + // implement a very stupid selection algorithm for chunks + let mut cur_pos = 0; + while chunks.len() != 0 { + let mut candidate = 0; + let mut candidate_dist = move_distance(cur_pos, chunks[candidate][0]); + for (i, chunk) in chunks.iter().enumerate().skip(1) { + if move_distance(cur_pos, chunk[0]) > candidate_dist { + candidate = i; + candidate_dist = move_distance(cur_pos, chunk[0]) + } + } + cur_pos = chunks[candidate][0]; + final_chunks.push(chunks.swap_remove(candidate)) + } + let final_instructions = final_chunks + .into_iter() + .flatten() + .map(|c| SEQUENCE[*c as usize]) + .collect_vec(); + + part1(&String::from_utf8_lossy(&final_instructions)) +} + +#[cfg(test)] +mod tests { + use rstest::rstest; + + use super::*; + + #[rstest] + #[case("roygbv", 11)] + #[case("vbgyor", 30)] + #[case("vvvvvv", 35)] + fn part1_example(#[case] input: &str, #[case] expected: u64) { + assert_eq!(part1(input), expected); + } + + #[rstest] + #[case("vrvbvg", 33)] + #[case("groovyyoyo", 55)] + #[case("roygbvroygbvroygbv", 103)] + fn part2_example(#[case] input: &str, #[case] expected: u64) { + assert_eq!(part2(input), expected); + } +}