From 79bdf55df512f0610a43a8d935b3fe81e88a15c7 Mon Sep 17 00:00:00 2001 From: Justin Worthe Date: Tue, 12 Dec 2017 07:22:45 +0200 Subject: Day 12: Grouping processes --- src/bin/day_12.rs | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/bin/day_12.rs (limited to 'src') diff --git a/src/bin/day_12.rs b/src/bin/day_12.rs new file mode 100644 index 0000000..39f05e9 --- /dev/null +++ b/src/bin/day_12.rs @@ -0,0 +1,52 @@ +extern crate advent_of_code_2017; +use advent_of_code_2017::*; + +use std::cmp; + +fn main() { + let args = AdventArgs::init(); + + let mut groups: Vec> = vec!(vec!(0)); //0 in the first group + + for line in args.input { + let mut words_iter = line.split_whitespace(); + let current: i32 = words_iter.next().unwrap().parse().unwrap(); + if find_group(&groups, current).is_none() { + groups.push(vec!(current)); + } + words_iter.next().unwrap(); //<-> + for other_str in words_iter { + let other: i32 = other_str.trim_right_matches(",").parse().unwrap(); + + match (find_group(&groups, current), find_group(&groups, other)) { + (Some(current_group), Some(other_group)) if current_group != other_group => { + merge_groups(&mut groups, current_group, other_group); + }, + (Some(_), Some(_)) => { + }, + (Some(current_group), None) => { + groups[current_group].push(other); + }, + (None, _) => panic!("Current group not found!") + }; + } + } + + if args.part == 1 { + println!("First group has {} members", groups[0].len()); + } else { + println!("Total of {} groups", groups.len()); + } +} + +fn find_group(groups: &Vec>, x: i32) -> Option { + groups.iter().position(|group| group.contains(&x)) +} + +fn merge_groups(groups: &mut Vec>, a: usize, b: usize) { + let src = cmp::max(a, b); + let dest = cmp::min(a, b); + + let mut from = groups.swap_remove(src); + groups[dest].append(&mut from) +} -- cgit v1.2.3