summaryrefslogtreecommitdiff
path: root/d03/src/main.rs
blob: d168a44629d85fc24681680edcf5c407d43f5de3 (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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use std::fs;

fn solve_part1(rows: &Vec<Vec<usize>>) -> usize {
    let mut num_valid: usize = 0;

    for row in rows {
        let mut sides = row.clone();

        sides.sort();
        if sides[0] + sides[1] > sides[2] {
            num_valid += 1;
        }
    }

    num_valid
}

fn solve_part2(rows: &Vec<Vec<usize>>) -> usize {
    let mut num_valid: usize = 0;

    // For each 3 consecutive rows of data
    for i in 0..(rows.len() / 3) {
        // For each of the 3 numbers per row
        for j in 0..3 {
            let mut sides = Vec::new();
            // For each row in this group of 3 rows
            for k in 0..3 {
                sides.push(rows[3 * i + k][j]);
            }

            sides.sort();
            if sides[0] + sides[1] > sides[2] {
                num_valid += 1;
            }
        }
    }

    num_valid
}

fn main() {
    // Read and parse triangle data from input text file
    let input = fs::read_to_string("input.txt").unwrap();
    let lines: Vec<&str> = input.lines().collect();
    let words: Vec<Vec<&str>> = lines
        .into_iter()
        .map(|l| l.split_ascii_whitespace().collect())
        .collect();
    let rows: Vec<Vec<usize>> = words
        .into_iter()
        .map(|w123| w123
            .into_iter()
            .map(|s| s.parse().unwrap())
            .collect())
        .collect();

    // Part 1 gives 993 for me
    println!("Part 1 solution: {}", solve_part1(&rows));

    // Part 2 gives 1849 for me
    println!("Part 2 solution: {}", solve_part2(&rows));
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn part1_example1() {
        let rows = vec![
            vec![5, 10, 25],
            vec![3,  4,  5],
        ];
        assert_eq!(solve_part1(&rows), 1);
    }

    #[test]
    fn part2_example1() {
        let rows = vec![
            vec![101, 301, 501],
            vec![102, 302, 502],
            vec![103, 303, 503],
            vec![201, 401, 601],
            vec![202, 402, 602],
            vec![203, 403, 603],
        ];
        assert_eq!(solve_part2(&rows), 6);
    }
}