diff --git a/2019/08/Cargo.toml b/2019/08/Cargo.toml index 785bc92..fee0bdf 100644 --- a/2019/08/Cargo.toml +++ b/2019/08/Cargo.toml @@ -7,3 +7,4 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +itertools = "0.8.2" diff --git a/2019/08/src/counter.rs b/2019/08/src/counter.rs index 772bb0f..0c65a84 100644 --- a/2019/08/src/counter.rs +++ b/2019/08/src/counter.rs @@ -12,7 +12,13 @@ impl Counter { Self { values: HashMap::new() } } - pub fn add(&mut self, collection: &[T]) { + pub fn of>(collection: C) -> Counter { + let mut counter = Counter::new(); + counter.add(collection); + counter + } + + pub fn add>(&mut self, collection: C) { for x in collection { self.values.insert(x.clone(), self.values.get(&x).unwrap_or(&0) + 1); } diff --git a/2019/08/src/main.rs b/2019/08/src/main.rs index 57eb834..c9277af 100644 --- a/2019/08/src/main.rs +++ b/2019/08/src/main.rs @@ -1,42 +1,29 @@ mod counter; use counter::Counter; +use itertools::Itertools; use std::io::BufRead; const WIDTH: usize = 25; const HEIGHT: usize = 6; fn main() { - let input: Vec<_> = std::io::stdin() - .lock() - .lines() - .next() - .unwrap() - .unwrap() - .chars() - .collect(); - let mut counters: Vec<_> = vec![]; - let mut chunks = input.chunks(WIDTH).peekable(); + let input = std::io::stdin().lock().lines().next().unwrap().unwrap(); + let chunked = input.chars().chunks(HEIGHT * WIDTH); + let layers = chunked.into_iter(); let mut img = vec!['2'; WIDTH * HEIGHT]; - let mut cur_pos = (0..WIDTH * HEIGHT).cycle(); - while chunks.peek().is_some() { - let mut counter = Counter::new(); - for _ in 0..HEIGHT { - let next_chunk = chunks.next().unwrap(); - for p in next_chunk { - let pos = cur_pos.next().unwrap(); - if let Some(&'2') = img.get(pos) { - img[pos] = *p; - } + let counters = layers.map(|layer| { + Counter::of(layer.enumerate().map(|(i, p)| { + if let Some(&'2') = img.get(i) { + img[i] = p } - counter.add(next_chunk); - } - counters.push(counter); - } + p + })) + }); - let fewest_zeros = counters.into_iter().min_by_key(|c| c['0']).unwrap(); + let fewest_zeros = counters.min_by_key(|c| c['0']).unwrap(); println!("Part 1: {}", fewest_zeros['1'] * fewest_zeros['2']); for line in img.chunks(WIDTH) { - println!("{}", line.into_iter().collect::().replace('0', " ")); + println!("{}", line.iter().collect::().replace('0', " ")); } }