summaryrefslogtreecommitdiff
path: root/2024/day01.rs
blob: 6f9251eb01d059b49e1844aee6876257cef883fd (plain)
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
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_mut)]
use std::env;
use std::fs::File;
use std::io::Read;

fn main() {
    let args: Vec<String> = env::args().collect();
    let filename = if args.len() == 1 {
        "in/".to_owned() + args[0].split('/').last().unwrap() + ".pzl"
    } else {
        args[1].clone()
    };
    let mut f = File::open(filename).expect("cannot open file");
    let mut content = String::new();
    f.read_to_string(&mut content).expect("cannot read file");
    let lines = content.trim_end().split("\n");

    let mut va: Vec<i32> = Vec::new();
    let mut vb: Vec<i32> = Vec::new();
    for line in lines {
        let (a, b) = line.split_once("   ").unwrap();
        va.push(a.parse().unwrap());
        vb.push(b.parse().unwrap());
        //println!("{} {}", l, r);
    }

    let mut vas = va.clone();
    let mut vbs = vb.clone();
    vas.sort();
    vbs.sort();
    let res1 = vas
        .iter()
        .zip(vbs.iter())
        .map(|(a, b)| (a - b).abs())
        .fold(0, |a, b| a + b);

    let res2 = va
        .iter()
        .map(|a| *a * (vb.iter().filter(move |b| *b == a).collect::<Vec<_>>().len() as i32))
        .fold(0, |a, b| a + b);

    println!("res1: {}", res1);
    println!("res2: {:?}", res2);
    assert_eq!(res1, 2970687);
    assert_eq!(res2, 23963899);
}