use std::error::Error; use std::fs::File; use std::io::{self, BufRead}; use std::vec::Vec; fn main() -> Result<(), Box> { let file = File::open("inputs/day23.txt")?; let mut lines = io::BufReader::new(file).lines().map(|l| l.unwrap()); let line = lines.nth(0).expect("No line in file."); let mut cups: Vec = line .chars() .map(|c| c.to_string().parse().expect("Can't parse number")) .collect(); let mut cur_pos = 0; for m in 1..101 { println!("Move: {}", m); println!("Cups: {:?}", cups); let cur_cup = cups[cur_pos]; println!("Current: {}", cur_cup); let mut taken = Vec::new(); for i in 0..3 { let cup = cups[(cur_pos + 1 + i) % cups.len()]; taken.push(cup); } println!("Taken: {:?}", taken); cups = cups .iter() .cloned() .filter(|c| !taken.iter().any(|oc| c == oc)) .collect(); let min = cups.iter().fold(cups[0], |a, b| usize::min(a, *b)); let max = cups.iter().fold(cups[0], |a, b| usize::max(a, *b)); let mut dest_cup = cur_cup; loop { dest_cup = if dest_cup < min { max } else { dest_cup - 1 }; if let Some(pos) = cups.iter().position(|c| *c == dest_cup) { println!("Dest: {}", dest_cup); for taken_cup in taken.iter().rev() { cups.insert(pos + 1, *taken_cup); } break; } } // Rotate cups to keep the current cup at the same index while cups[cur_pos] != cur_cup { let cup = cups.remove(0); cups.push(cup); } cur_pos = (cur_pos + 1) % cups.len(); println!("=============================") } // Rotate cups make 1 the first while cups[0] != 1 { let cup = cups.remove(0); cups.push(cup); } let answer = cups.iter().skip(1).fold(0, |a, c| a * 10 + c); println!("Answer: {}", answer); Ok(()) } #[cfg(test)] mod tests { use crate::*; }