summaryrefslogtreecommitdiffstats
path: root/src/bin/2021/day7.rs
blob: 56eaeb11fb83189c9a7ab0a551828ec1ed908bbd (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
use advent_of_code::prelude::*;

pub fn parse(fh: File) -> Result<Vec<usize>> {
    Ok(parse::split(fh, b',').collect())
}

pub fn part1(crabs: Vec<usize>) -> Result<usize> {
    Ok((0..=crabs.iter().copied().max().unwrap())
        .map(|start| {
            crabs.iter().copied().map(|crab| crab.abs_diff(start)).sum()
        })
        .min()
        .unwrap())
}

pub fn part2(crabs: Vec<usize>) -> Result<usize> {
    Ok((0..=crabs.iter().copied().max().unwrap())
        .map(|start| {
            crabs
                .iter()
                .copied()
                .map(|crab| {
                    let diff = crab.abs_diff(start);
                    diff * (diff + 1) / 2
                })
                .sum()
        })
        .min()
        .unwrap())
}

#[test]
fn test() {
    assert_eq!(
        part1(parse(parse::data(2021, 7).unwrap()).unwrap()).unwrap(),
        333755
    );
    assert_eq!(
        part2(parse(parse::data(2021, 7).unwrap()).unwrap()).unwrap(),
        94017638
    );
}