From c807f716daeac4cad24c665cea4f49268dbe2e02 Mon Sep 17 00:00:00 2001 From: Alpha Chen Date: Fri, 7 Dec 2018 13:11:59 -0800 Subject: [PATCH] [2018][rust][07] refactoring --- 2018/rust/src/bin/day_07.rs | 63 ++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 25 deletions(-) diff --git a/2018/rust/src/bin/day_07.rs b/2018/rust/src/bin/day_07.rs index 6cbc0d8..7b627c1 100644 --- a/2018/rust/src/bin/day_07.rs +++ b/2018/rust/src/bin/day_07.rs @@ -16,29 +16,22 @@ fn main() -> Result<(), Box> { } fn solve(input: &str) -> Result> { - let instructions: Instructions = input.parse()?; - let output = part_one(instructions).iter().map(char::to_string).collect(); + let mut assembly: Assembly = input.parse()?; + let output = part_one(&mut assembly).iter().map(char::to_string).collect(); Ok(output) } -#[allow(dead_code)] -fn part_one(instructions: Instructions) -> Vec { - let mut steps = instructions.steps; +fn part_two usize>(assembly: Assembly, worker_count: usize, step_time: F) {} +#[allow(dead_code)] +fn part_one(assembly: &mut Assembly) -> Vec { let mut output = Vec::new(); - while !steps.is_empty() { - let mut ready: Vec<_> = steps - .iter() - .filter(|(_, v)| v.is_empty()) - .map(|(k, _)| k) - .collect(); - ready.sort(); - let done = *ready[0]; + while !assembly.is_done() { + let mut available = assembly.available_steps(); + available.sort(); + let done = *available[0]; - steps.remove(&done); - for dependencies in steps.values_mut() { - dependencies.remove(&done); - } + assembly.finish(&done); output.push(done); } @@ -58,24 +51,44 @@ Step D must be finished before step E can begin. Step F must be finished before step E can begin. "; - let instructions: Instructions = input.parse().unwrap(); - let output = part_one(instructions); + let mut assembly: Assembly = input.parse().unwrap(); + let output = part_one(&mut assembly); assert_eq!(output, vec!['C', 'A', 'B', 'D', 'F', 'E']); } -struct Instructions { +struct Assembly { steps: HashMap>, } -impl FromStr for Instructions { +impl Assembly { + fn is_done(&self) -> bool { + self.steps.is_empty() + } + + fn available_steps(&self) -> Vec<&char> { + self.steps + .iter() + .filter(|(_, v)| v.is_empty()) + .map(|(k, _)| k) + .collect() + } + + fn finish(&mut self, step: &char) { + self.steps.remove(step); + for dependencies in self.steps.values_mut() { + dependencies.remove(step); + } + } +} + +impl FromStr for Assembly { type Err = Box; fn from_str(s: &str) -> Result { let re = Regex::new(r"^Step (\w).*step (\w)").unwrap(); let mut steps = HashMap::new(); - s - .trim() + s.trim() .lines() .flat_map(|x| re.captures(x)) .map(|x| { @@ -84,13 +97,13 @@ impl FromStr for Instructions { .map(|x| x.as_str().chars().next().unwrap()) .collect::>() }) - .map(|x| (x[1], x[2])) + .map(|x| (x[1], x[2])) .for_each(|(x, y)| { steps.entry(x).or_insert_with(HashSet::new); let entry = steps.entry(y).or_insert_with(HashSet::new); entry.insert(x); }); - Ok(Instructions{steps}) + Ok(Assembly { steps }) } }