summary refs log tree commit diff homepage
path: root/2016/src/bin/day06.rs
blob: 7f8a5165f143a7fe6e81f848a8572056d5873622 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use std::collections::HashMap;
use std::io::{self, Read};

fn frequencies(chars: &[char]) -> HashMap<char, u32> {
    let mut map = HashMap::new();
    for &ch in chars {
        *map.entry(ch).or_insert(0) += 1;
    }
    map
}

fn solve1(input: &str) -> String {
    let len = input.find('\n').unwrap_or(input.len());
    let mut columns = vec![Vec::new(); len];

    for line in input.lines() {
        for (i, ch) in line.chars().enumerate() {
            columns[i].push(ch);
        }
    }

    columns.into_iter()
        .map(|column| frequencies(&column))
        .map(IntoIterator::into_iter)
        .map(|iter| iter.max_by_key(|&(_, v)| v))
        .map(Option::unwrap)
        .map(|(ch, _)| ch)
        .collect()
}

fn solve2(input: &str) -> String {
    let len = input.find('\n').unwrap_or(input.len());
    let mut columns = vec![Vec::new(); len];

    for line in input.lines() {
        for (i, ch) in line.chars().enumerate() {
            columns[i].push(ch);
        }
    }

    columns.into_iter()
        .map(|column| frequencies(&column))
        .map(IntoIterator::into_iter)
        .map(|iter| iter.min_by_key(|&(_, v)| v))
        .map(Option::unwrap)
        .map(|(ch, _)| ch)
        .collect()
}

fn main() {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input).unwrap();

    println!("Part 1: {}", solve1(&input));
    println!("Part 2: {}", solve2(&input));
}

#[cfg(test)]
const TEST_INPUT: &'static str = "
eedadn
drvtee
eandsr
raavrd
atevrs
tsrnev
sdttsa
rasrtv
nssdts
ntnada
svetve
tesnvt
vntsnd
vrdear
dvrsen
enarar
";


#[test]
fn part1() {
    assert_eq!("easter", solve1(TEST_INPUT.trim()));
}

#[test]
fn part2() {
    assert_eq!("advent", solve2(TEST_INPUT.trim()));
}