From 93e057ed472db7c3bc5d579969a0ec15ee4ed905 Mon Sep 17 00:00:00 2001 From: Curtis McEnroe Date: Tue, 6 Dec 2016 01:32:18 -0500 Subject: Day 6, less gross? --- src/bin/day06.rs | 62 ++++++++++++-------------------------------------------- 1 file changed, 13 insertions(+), 49 deletions(-) (limited to 'src') diff --git a/src/bin/day06.rs b/src/bin/day06.rs index bdd9147..72ee658 100644 --- a/src/bin/day06.rs +++ b/src/bin/day06.rs @@ -1,46 +1,12 @@ +use std::collections::HashMap; use std::io::{self, Read}; -struct Runs { - inner: I, - current: Option, - count: usize, -} - -impl From for Runs { - fn from(iter: I) -> Self { - Runs { - inner: iter, - current: None, - count: 0, - } - } -} - -// Gross. -impl> Iterator for Runs { - type Item = (T, usize); - - fn next(&mut self) -> Option<(T, usize)> { - for c in &mut self.inner { - match self.current { - None => { - self.current = Some(c); - self.count = 1; - }, - Some(r) if r == c => { - self.count += 1; - }, - Some(r) => { - self.current = Some(c); - let run = self.count; - self.count = 1; - return Some((r, run)); - }, - } - } - - self.current.take().map(|c| (c, self.count)) +fn frequencies(chars: &[char]) -> HashMap { + let mut map = HashMap::new(); + for &ch in chars { + *map.entry(ch).or_insert(0) += 1; } + map } fn solve(input: &str) -> String { @@ -48,19 +14,17 @@ fn solve(input: &str) -> String { let mut columns = vec![Vec::new(); len]; for line in input.lines() { - for (i, c) in line.chars().enumerate() { - columns[i].push(c); + for (i, ch) in line.chars().enumerate() { + columns[i].push(ch); } } columns.into_iter() - .map(|mut column| { - column.sort(); - Runs::from(column.into_iter()) - .max_by_key(|run| run.1) - .unwrap() - .0 - }) + .map(|column| frequencies(&column)) + .map(IntoIterator::into_iter) + .map(|iter| iter.max_by_key(|&(_, v)| v)) + .map(Option::unwrap) + .map(|(ch, _)| ch) .collect() } -- cgit 1.4.1