test / AoC 2024 (push) Failing after 22s
git-subtree-dir: 2026 git-subtree-mainline:70a284ca0fgit-subtree-split:144d63eb66
89 lines
2.5 KiB
Rust
89 lines
2.5 KiB
Rust
use aoc_runner_derive::{aoc, aoc_generator};
|
|
use itertools::Itertools;
|
|
|
|
#[aoc_generator(day2)]
|
|
fn parse(input: &str) -> Vec<u8> {
|
|
input
|
|
.as_bytes()
|
|
.iter()
|
|
.map(|i| SEQUENCE.iter().position(|c| c == i).unwrap() as u8)
|
|
.collect_vec()
|
|
}
|
|
|
|
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: &[u8]) -> u64 {
|
|
let mut cur_pos = 0i64;
|
|
|
|
for i in input {
|
|
cur_pos += move_distance((cur_pos % SEQUENCE.len() as i64) as u8, *i);
|
|
}
|
|
|
|
cur_pos as u64
|
|
}
|
|
|
|
#[aoc(day2, part2)]
|
|
fn part2(input: &[u8]) -> u64 {
|
|
let mut instructions = input.to_owned();
|
|
|
|
// bring same instructions together, but this will minimize the distance between chunks so we need to spread them again
|
|
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.
|
|
// we are already sorted so there is probably an optimal way to place them directly.
|
|
// maybe alternating once we find the 'pivot' or something.
|
|
// but this is plenty fast.
|
|
let mut cur_pos = 0;
|
|
while !chunks.is_empty() {
|
|
let mut candidate = 0;
|
|
let mut candidate_dist = move_distance(cur_pos, chunks[candidate][0]);
|
|
for (i, chunk) in chunks.iter().enumerate().skip(1) {
|
|
let dist = move_distance(cur_pos, chunk[0]);
|
|
if dist > candidate_dist {
|
|
candidate = i;
|
|
candidate_dist = dist;
|
|
}
|
|
}
|
|
cur_pos = chunks[candidate][0];
|
|
final_chunks.push(chunks.remove(candidate))
|
|
}
|
|
let final_instructions = final_chunks.into_iter().flatten().copied().collect_vec();
|
|
|
|
part1(&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(&parse(input)), expected);
|
|
}
|
|
|
|
#[rstest]
|
|
#[case("vrvbvg", 33)]
|
|
#[case("groovyyoyo", 55)]
|
|
#[case("roygbvroygbvroygbv", 103)]
|
|
fn part2_example(#[case] input: &str, #[case] expected: u64) {
|
|
assert_eq!(part2(&parse(input)), expected);
|
|
}
|
|
}
|