This commit is contained in:
JonOfUs 2023-12-08 11:59:38 +01:00
parent 9790369331
commit a0b969332b

View file

@ -1,6 +1,5 @@
use std::{collections::HashMap, fs}; use std::{collections::HashMap, fs};
pub fn solve() { pub fn solve() {
let path = "res/08/input"; let path = "res/08/input";
@ -10,10 +9,11 @@ pub fn solve() {
let (instr_raw, map_raw) = contents.split_once("\n\n").unwrap(); let (instr_raw, map_raw) = contents.split_once("\n\n").unwrap();
let instr: Vec<char> = instr_raw.chars().collect(); let instr: Vec<char> = instr_raw.chars().collect();
let map: HashMap<String, (String,String)> = map_raw let map: HashMap<String, (String, String)> = map_raw
.lines() .lines()
.map(|line| { .map(|line| {
let (src, dst1, dst2) = scan_fmt!(line, "{} = ({}, {})", String, String, String).unwrap(); let (src, dst1, dst2) =
scan_fmt!(line, "{} = ({}, {})", String, String, String).unwrap();
(src, (dst1, dst2)) (src, (dst1, dst2))
}) })
@ -21,46 +21,40 @@ pub fn solve() {
let mut curr = String::from("AAA"); let mut curr = String::from("AAA");
let mut i = 0; let mut i = 0;
while curr != String::from("ZZZ") { while curr != String::from("ZZZ") {
dbg!(curr.as_str()); curr = match instr[i % instr.len()] {
curr = match instr[i % instr.len()] {
'L' => map.get(curr.as_str()).unwrap().0.clone(), 'L' => map.get(curr.as_str()).unwrap().0.clone(),
'R' => map.get(curr.as_str()).unwrap().1.clone(), 'R' => map.get(curr.as_str()).unwrap().1.clone(),
_ => panic!() _ => panic!(),
}; };
i+=1; i += 1;
}
println!("Result 1: {}", i); println!("Result 1: {}", i);
let mut curr: Vec<String> = map
let mut curr: Vec<String> = map.keys() .keys()
.filter(|s| s.ends_with("A")) .filter(|s| s.ends_with("A"))
.map(|s| s.clone()) .map(|s| s.clone())
.collect(); .collect();
let mut i = 0; let mut i = 0;
let mut steps: Vec<usize> = vec![0; curr.len()]; let mut steps: Vec<usize> = vec![0; curr.len()];
while steps.iter().any(|s| *s == 0) { while steps.iter().any(|s| *s == 0) {
(0..curr.len()) (0..curr.len()).for_each(|j| {
.for_each(|j| { if curr[j].ends_with("Z") && steps[j] == 0 {
if curr[j].ends_with("Z") && steps[j] == 0 { steps[j] = i;
steps[j] = i; } else if steps[j] == 0 {
} else if steps[j] == 0 { curr[j] = match instr[i % instr.len()] {
curr[j] = match instr[i % instr.len()] { 'L' => map.get(curr[j].as_str()).unwrap().0.clone(),
'L' => map.get(curr[j].as_str()).unwrap().0.clone(), 'R' => map.get(curr[j].as_str()).unwrap().1.clone(),
'R' => map.get(curr[j].as_str()).unwrap().1.clone(), _ => panic!(),
_ => panic!()
}
} }
}); }
i+=1; });
i += 1;
} }
let result = steps.iter() let result = steps.iter().fold(1, |x, y| num::integer::lcm(x, *y));
.fold(1, |x,y| {
num::integer::lcm(x,*y)
});
println!("Result 2: {}", result); println!("Result 2: {}", result);
}
}