Clean up D8

This commit is contained in:
kageru 2019-12-08 15:32:02 +01:00
parent 2e5a3f5ae3
commit 3a3283bf72
Signed by: kageru
GPG Key ID: 8282A2BEA4ADA3D2
3 changed files with 21 additions and 27 deletions

View File

@ -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"

View File

@ -12,7 +12,13 @@ impl <T: Hash + Eq + Clone> Counter<T> {
Self { values: HashMap::new() }
}
pub fn add(&mut self, collection: &[T]) {
pub fn of<C: IntoIterator<Item=T>>(collection: C) -> Counter<T> {
let mut counter = Counter::new();
counter.add(collection);
counter
}
pub fn add<C: IntoIterator<Item=T>>(&mut self, collection: C) {
for x in collection {
self.values.insert(x.clone(), self.values.get(&x).unwrap_or(&0) + 1);
}

View File

@ -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::<String>().replace('0', " "));
println!("{}", line.iter().collect::<String>().replace('0', " "));
}
}