aoc/year2017/
day02.rs

1//! # Corruption Checksum
2//!
3//! Part two is `O(n²)` complexity but at least we can reduce by a factor of two by sorting
4//! each line first, allowing us to only compare each number against those that are greater.
5//! As a minor benefit this makes part one faster too.
6use crate::util::parse::*;
7
8type Input = Vec<Vec<u32>>;
9
10pub fn parse(input: &str) -> Input {
11    input
12        .lines()
13        .map(|line| {
14            let mut values: Vec<_> = line.iter_unsigned().collect();
15            values.sort_unstable();
16            values
17        })
18        .collect()
19}
20
21pub fn part1(input: &Input) -> u32 {
22    input.iter().map(|values| values[values.len() - 1] - values[0]).sum()
23}
24
25pub fn part2(input: &Input) -> u32 {
26    input
27        .iter()
28        .map(|values| {
29            for i in 0..values.len() {
30                for j in i + 1..values.len() {
31                    if values[j] % values[i] == 0 {
32                        return values[j] / values[i];
33                    }
34                }
35            }
36            unreachable!()
37        })
38        .sum()
39}