summaryrefslogtreecommitdiffstats
path: root/src/2021/7/mod.rs
blob: 8ddd46ead4d1183822f17d44a2f0c1c059416267 (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 crate::prelude::*;

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

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

pub fn part2(crabs: Vec<i64>) -> Result<i64> {
    Ok((0..=crabs.iter().copied().max().unwrap())
        .map(|start| {
            crabs
                .iter()
                .copied()
                .map(|crab| {
                    let diff = (crab - start).abs();
                    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
    );
}