day8 part2

This commit is contained in:
Candygoblen123 2023-12-10 16:03:23 -05:00
parent 7dec743fbb
commit d5395fc349
No known key found for this signature in database
GPG Key ID: 577DA64EBEF10385

View File

@ -19,11 +19,44 @@ fn main() {
(line[0], (children[0], children[1]))
}).collect();
let mut cur_node = "AAA";
let mut step_queue = VecDeque::from(directions);
let starts: Vec<_> = nodes.keys().filter(|x| x.ends_with('A')).collect();
let dists: Vec<_> = starts.iter().map(|start| dist(&start, &directions, &nodes)).collect();
let gcf = gcf(&dists);
let step_count = gcf * dists.iter().map(|value| value / gcf).product::<i64>();
println!("{:?}", step_count);
}
fn gcf(values: &Vec<i64>) -> i64 {
let mut gcf = values[0];
for val in values {
gcf = find_gcf(gcf, *val);
if gcf == 1 {
return 1;
}
}
gcf
}
fn find_gcf(a: i64, b: i64) -> i64 {
if a == 0 {
return b;
}
find_gcf(b % a, a)
}
fn dist(cur_node: &str, directions: &Vec<Direction>, nodes: &HashMap<&str, (&str, &str)>) -> i64 {
let mut cur_node = cur_node;
let mut step_queue: VecDeque<Direction> = VecDeque::from(directions.clone());
let mut step_count = 0;
while cur_node != "ZZZ" {
while !cur_node.ends_with('Z') {
step_count += 1;
let cur_step = step_queue.pop_front().unwrap();
match cur_step {
@ -33,11 +66,57 @@ fn main() {
step_queue.push_back(cur_step);
}
println!("{:?}", step_count);
return step_count;
}
#[derive(Clone)]
#[derive(Debug)]
enum Direction {
Left,
Right
}
// use std::{fs, collections::{HashMap, VecDeque}};
// fn main() {
// let input = fs::read_to_string("input.txt").unwrap();
// let input: Vec<_> = input.split("\n\n").collect();
// let (directions, nodes) = (input[0], input[1]);
// let directions: Vec<_> = directions.chars().map(|char| {
// match char {
// 'L' => Direction::Left,
// 'R' => Direction::Right,
// _ => panic!("Invalid direction!")
// }
// }).collect();
// let nodes: HashMap<&str, (&str, &str)> = nodes.split('\n')
// .map(|line| {
// let line = line.split('=').map(|x| x.trim()).collect::<Vec<_>>();
// let children: Vec<_> = line[1].trim_matches(|c| c == '(' || c == ')').split(", ").collect();
// (line[0], (children[0], children[1]))
// }).collect();
// let mut cur_node = "AAA";
// let mut step_queue = VecDeque::from(directions);
// let mut step_count = 0;
// while cur_node != "ZZZ" {
// step_count += 1;
// let cur_step = step_queue.pop_front().unwrap();
// match cur_step {
// Direction::Left => cur_node = nodes[cur_node].0,
// Direction::Right => cur_node = nodes[cur_node].1,
// }
// step_queue.push_back(cur_step);
// }
// println!("{:?}", step_count);
// }
// #[derive(Debug)]
// enum Direction {
// Left,
// Right
// }