Simulate chains simultaneously

This commit is contained in:
max.nuding 2022-12-09 08:46:16 +01:00
parent 1e9d553c22
commit fe66170e3e
Failed to extract signature

View File

@ -1,5 +1,6 @@
use crate::read;
use std::collections::HashSet;
use itertools::Itertools;
#[derive(Debug, PartialEq, Eq, Default, Clone, Hash)]
struct Position {
@ -59,43 +60,70 @@ impl Position {
}
}
struct Chain {
pub knots: Vec<Position>,
visited: HashSet<Position>
}
impl Chain {
pub fn new(num_knots: usize) -> Self {
Self {
knots: vec![Position::default(); num_knots],
visited: HashSet::with_capacity(10000)
}
}
pub fn num_visited(&self) -> usize {
self.visited.len()
}
pub fn move_knots(&mut self, direction: &str, count: usize) {
let move_head_func = match direction {
"R" => Position::move_right,
"U" => Position::move_up,
"L" => Position::move_left,
"D" => Position::move_down,
_ => unreachable!(),
};
for _c in 0..count {
self.knots[0] = move_head_func(&mut self.knots[0]);
for i in 1..self.knots.len() {
self.knots[i] = self.knots[i].follow_head(&self.knots[i - 1]);
}
self.visited.insert(self.knots.last().unwrap().clone());
}
}
}
pub fn run() {
let res = simulate(vec![2, 10]);
#[cfg(feature = "part1")]
{
println!("Day 9, Part 01: {}", simulate(2));
println!("Day 9, Part 01: {}", res[0]);
}
#[cfg(feature = "part2")]
{
println!("Day 9, Part 02: {}", simulate(10));
println!("Day 9, Part 02: {}", res[1]);
}
}
pub fn simulate(num_knots: usize) -> usize {
let mut visited: HashSet<Position> = HashSet::new();
let mut knots = vec![Position::default(); num_knots];
let input = read("09");
let lines = input.lines();
for line in lines {
if line.is_empty() {
continue;
}
let (dir, count) = line.split_once(' ').unwrap();
let count = count.parse().unwrap();
for _c in 0..count {
knots[0] = match dir {
"R" => knots[0].move_right(),
"U" => knots[0].move_up(),
"L" => knots[0].move_left(),
"D" => knots[0].move_down(),
_ => unreachable!(),
};
for i in 1..knots.len() {
knots[i] = knots[i].follow_head(&knots[i - 1]);
}
visited.insert(knots.last().unwrap().clone());
}
}
visited.len()
fn simulate(chain_sizes: Vec<usize>) -> Vec<usize> {
let chains = read("09")
.lines()
.filter(|l|!l.is_empty())
.map(|l|l.split_once(' ').unwrap())
.map(|(dir, count)|(dir, count.parse::<usize>().unwrap()))
.fold(chain_sizes
.iter()
.map(|c|Chain::new(*c))
.collect_vec(),
|mut chains, (dir, count)| {
chains
.iter_mut()
.for_each(|chain|chain.move_knots(dir, count));
chains
});
chains.iter().map(|c|c.num_visited()).collect()
}