summaryrefslogtreecommitdiff
path: root/2019/rust/day03/src/main.rs
blob: fa26cac74cc42b86b4decfc8d736d615998d4f9b (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
use std::cmp::Ord;
use std::cmp::Ordering;
use std::collections::{BTreeMap, HashSet};
use std::io::{self, BufRead};

struct WireStep {
    dir : char,
    len : i32,
}

type WirePath = Vec<WireStep>;

#[derive(Clone, Debug)]
struct WirePoint {
    wire: u8,
    steps: usize,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd)]
// https://newspaint.wordpress.com/2016/07/05/implementing-custom-sort-for-btree-in-rust/
struct MapCoords {
    x: i32,
    y: i32,
}

type MapPoint = Vec<WirePoint>;
type WireMap = BTreeMap<MapCoords, MapPoint>;

impl Ord for MapCoords {
    fn cmp(&self, other:&Self) -> Ordering {
        let self_distance = i32::abs(self.x) + i32::abs(self.y);
        let other_distance = i32::abs(other.x) + i32::abs(other.y);

        if self_distance < other_distance {
            Ordering::Less
        } else if self_distance > other_distance {
            Ordering::Greater
        } else if self.y < other.y {
            Ordering::Less
        } else if self.y > other.y {
            Ordering::Greater
        } else if self.x < other.x {
            Ordering::Less
        } else if self.x > other.x {
            Ordering::Greater
        } else {
            Ordering::Equal
        }
    }
}

fn read_input() -> Vec<WirePath> {
    let stdin = io::stdin();

    stdin.lock().lines()
        .map(|line| {
            line.unwrap().split(',').map(|s| WireStep {
                dir: s.chars().next().unwrap(),
                len: s.get(1..).unwrap().parse().unwrap(),
            }).collect()
        }).collect()
}

fn map_wire(wire: u8, path:&WirePath, map:&mut WireMap) {
    let mut x = 0;
    let mut y = 0;

    let wp = WirePoint { wire, steps: 0 };
    let mp = map.entry(MapCoords{x, y}).or_insert(vec![]);
    mp.push(wp);
    let mut steps = 0;
    for trace in path.iter() {
        for _ in 0..trace.len {
            match trace.dir {
                'U' => y -= 1,
                'D' => y += 1,
                'R' => x += 1,
                'L' => x -= 1,
                d => panic!("Invalid direction {}", d),
            }
            steps += 1;
            let wp = WirePoint { wire, steps };
            let mp = map.entry(MapCoords{x, y}).or_insert(vec![]);
            mp.push(wp);
        }
    }
}

fn create_map(paths:&Vec<WirePath>, map:&mut WireMap) {
    let mut wire_id = 1;
    for path in paths.iter() {
        map_wire(wire_id, path, map);
        wire_id += 1;
    }
}

fn find_intersections(wire_map:&WireMap) -> WireMap {
    let mut ret = WireMap::new();
    for (coords, wiring) in wire_map {
        let wire_crossings = wiring.iter().map(|w| { w.wire }).collect::<HashSet<u8>>().len();
        if wire_crossings > 1 && ! (coords.x == 0 && coords.y == 0) {
            ret.insert(*coords, wiring.to_vec());
        }
    }

    ret
}

fn first_puzzle(wire_paths:&Vec<WirePath>) -> Option<usize> {
    let mut wire_map:WireMap = BTreeMap::new();

    create_map(&wire_paths, &mut wire_map);
    let intersections = find_intersections(&wire_map);

    match intersections.iter().next() {
        Some((c, _)) => Some((i32::abs(c.x) + i32::abs(c.y)) as usize),
        _            => None,
    }
}

fn second_puzzle(wire_paths:&Vec<WirePath>) -> Option<usize> {
    let mut wire_map:WireMap = BTreeMap::new();

    create_map(&wire_paths, &mut wire_map);
    let intersections = find_intersections(&wire_map);

    let lengths : Vec<usize> = intersections.iter().map(|(_, wiring)| {
        wiring.iter().map(|w| { w.steps }).sum()
    }).collect();

    lengths.into_iter().min()
}

fn main() {
    let wire_paths = read_input();

    let first = first_puzzle(&wire_paths);
    match first {
        Some(s) => println!("Solution to first part: {}.", s),
        _       => println!("No solution found for first part."),
    }

    let second = second_puzzle(&wire_paths);
    match second {
        Some(s) => println!("Solution to second part: {}.", s),
        _       => println!("No solution found for second part."),
    }
}