day2: both parts (oops)

This commit is contained in:
ktims committed 2026-12-01 22:48:44 -07:00
1 parent 4672422352
commit 5507b187fd
3 files changed
+93 -1

No files matched your search

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

+4 -1
View File
@@ -1,8 +1,11 @@
<!-- AOC TILES BEGIN --> <!-- AOC TILES BEGIN -->
<h1 align="center"> <h1 align="center">
2026 - 2 ⭐ - Rust 2026 - 4 ⭐ - Rust
</h1> </h1>
<a href="src/day1.rs"> <a href="src/day1.rs">
<img src=".aoc_tiles/tiles/2026/01.png" width="200"> <img src=".aoc_tiles/tiles/2026/01.png" width="200">
</a> </a>
<a href="src/day2.rs">
<img src=".aoc_tiles/tiles/2026/02.png" width="200">
</a>
<!-- AOC TILES END --> <!-- AOC TILES END -->
+89
View File
@@ -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);
}
}