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};
pub fn solve() {
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: Vec<char> = instr_raw.chars().collect();
let map: HashMap<String, (String,String)> = map_raw
let map: HashMap<String, (String, String)> = map_raw
.lines()
.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))
})
@ -21,46 +21,40 @@ pub fn solve() {
let mut curr = String::from("AAA");
let mut i = 0;
while curr != String::from("ZZZ") {
dbg!(curr.as_str());
curr = match instr[i % instr.len()] {
while curr != String::from("ZZZ") {
curr = match instr[i % instr.len()] {
'L' => map.get(curr.as_str()).unwrap().0.clone(),
'R' => map.get(curr.as_str()).unwrap().1.clone(),
_ => panic!()
_ => panic!(),
};
i+=1;
i += 1;
}
println!("Result 1: {}", i);
let mut curr: Vec<String> = map.keys()
let mut curr: Vec<String> = map
.keys()
.filter(|s| s.ends_with("A"))
.map(|s| s.clone())
.collect();
let mut i = 0;
let mut steps: Vec<usize> = vec![0; curr.len()];
while steps.iter().any(|s| *s == 0) {
(0..curr.len())
.for_each(|j| {
if curr[j].ends_with("Z") && steps[j] == 0 {
steps[j] = i;
} else if steps[j] == 0 {
curr[j] = match instr[i % instr.len()] {
'L' => map.get(curr[j].as_str()).unwrap().0.clone(),
'R' => map.get(curr[j].as_str()).unwrap().1.clone(),
_ => panic!()
}
(0..curr.len()).for_each(|j| {
if curr[j].ends_with("Z") && steps[j] == 0 {
steps[j] = i;
} else if steps[j] == 0 {
curr[j] = match instr[i % instr.len()] {
'L' => map.get(curr[j].as_str()).unwrap().0.clone(),
'R' => map.get(curr[j].as_str()).unwrap().1.clone(),
_ => panic!(),
}
});
i+=1;
}
});
i += 1;
}
let result = steps.iter()
.fold(1, |x,y| {
num::integer::lcm(x,*y)
});
let result = steps.iter().fold(1, |x, y| num::integer::lcm(x, *y));
println!("Result 2: {}", result);
}
}