DEVELOPMENT ENVIRONMENT

~liljamo/aoc2024

ref: f0ad4ff4a1b8467ca6a2999b70edf8d37db5de1f aoc2024/src/day1/mod.rs -rw-r--r-- 1.5 KiB
f0ad4ff4Jonni Liljamo feat: day1 a month ago
                                                                                
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
use std::{
    fs::File,
    io::{BufRead, BufReader},
    path::Path,
};

pub fn solve(input: &Path) -> anyhow::Result<()> {
    println!("part one: {}", part_one(input)?);
    println!("part two: {}", part_two(input)?);

    Ok(())
}

fn part_one(input: &Path) -> anyhow::Result<i32> {
    let reader = BufReader::new(File::open(input)?);

    let mut first: Vec<i32> = vec![];
    let mut second: Vec<i32> = vec![];
    for line in reader.lines() {
        let line = line?;
        let mut numbers = line.split_whitespace();
        first.push(numbers.next().unwrap().parse()?);
        second.push(numbers.next().unwrap().parse()?);
    }
    first.sort();
    second.sort();
    let mut answer = 0;
    for (i, f) in first.into_iter().enumerate() {
        answer += (f - second[i]).abs();
    }

    Ok(answer)
}

fn part_two(input: &Path) -> anyhow::Result<i32> {
    let reader = BufReader::new(File::open(input)?);

    let mut first: Vec<i32> = vec![];
    let mut second: Vec<i32> = vec![];
    for line in reader.lines() {
        let line = line?;
        let mut numbers = line.split_whitespace();
        first.push(numbers.next().unwrap().parse()?);
        second.push(numbers.next().unwrap().parse()?);
    }
    let mut answer = 0;
    for f in first {
        let amount = second
            .clone()
            .into_iter()
            .filter(|&s| s == f)
            .collect::<Vec<i32>>()
            .len();
        answer += f * amount as i32;
    }

    Ok(answer)
}