add day 15

This commit is contained in:
timeshifter
2026-07-02 13:06:20 +02:00
parent 7f1b82f7db
commit c568871f4d
5 changed files with 120 additions and 0 deletions
+99
View File
@@ -0,0 +1,99 @@
#[cfg(debug_assertions)]
const FILENAME: &str = "example.txt";
#[cfg(not(debug_assertions))]
const FILENAME: &str = "input.txt";
fn main() {
let mut discs: Vec<_> = std::fs::read_to_string(FILENAME)
.unwrap()
.lines()
.map(Disc::parse)
.collect();
part_1(&discs);
discs.push(Disc {
positions: 11,
current_position: 0,
});
part_1(&discs);
}
fn part_1(discs: &[Disc]) {
let mut initial_state = Simulation::new(discs);
let mut ball_drop_time = 0;
loop {
let mut simulation = initial_state.clone();
let success = simulation.run();
if success {
break;
}
ball_drop_time += 1;
initial_state.advance_discs();
}
println!("{ball_drop_time}")
}
#[derive(Clone, Debug)]
struct Simulation {
discs: Vec<Disc>,
}
impl Simulation {
fn new(discs: &[Disc]) -> Self {
Self {
discs: discs.to_vec(),
}
}
fn run(&mut self) -> bool {
let mut ball = 0;
loop {
ball += 1;
self.advance_discs();
if let Some(disc) = self.discs.get(ball - 1) {
if disc.current_position != 0 {
return false;
}
} else {
return true;
}
}
}
fn advance_discs(&mut self) {
self.discs.iter_mut().for_each(|disc| disc.advance());
}
}
#[derive(Debug, Clone)]
struct Disc {
positions: usize,
current_position: usize,
}
impl Disc {
fn parse(s: &str) -> Self {
let mut iter = s.split_whitespace();
let positions = iter.nth(3).unwrap().parse().unwrap();
let mut last_iter = iter.next_back().unwrap().chars();
last_iter.next_back();
let current_position = last_iter.collect::<String>().parse().unwrap();
Self {
positions,
current_position,
}
}
fn advance(&mut self) {
self.current_position += 1;
self.current_position %= self.positions;
}
}