summaryrefslogtreecommitdiff
path: root/2023/src/bin/day_25.rs
blob: 7bd37519ce250260193b8d5c68bb6909de15bd62 (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
149
150
151
152
153
154
use nom::{
    bytes::complete::tag,
    character::complete::{alpha1, line_ending, space1},
    combinator::map,
    multi::separated_list1,
    sequence::separated_pair,
    IResult,
};
use std::{collections::BTreeMap, fs};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let input = fs::read_to_string("inputs/day_25.txt")?;
    let parsed = Circuit::parser(&input).unwrap().1;
    let three_cut_partition_sizes = parsed.find_non_zero_three_cut_partition_sizes();
    dbg!(&three_cut_partition_sizes);
    dbg!(three_cut_partition_sizes.0 * three_cut_partition_sizes.1);

    Ok(())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct VertexId(usize);

#[derive(Debug)]
struct Circuit {
    wires: Vec<Vec<VertexId>>,
}

#[derive(Debug, Clone, Eq)]
struct Edge {
    a: VertexId,
    b: VertexId,
}

impl PartialEq for Edge {
    fn eq(&self, other: &Self) -> bool {
        (self.a == other.a && self.b == other.b) || (self.a == other.b && self.b == other.a)
    }
}

impl Circuit {
    fn parser(input: &str) -> IResult<&str, Self> {
        map(
            separated_list1(
                line_ending,
                separated_pair(
                    map(alpha1, |s: &str| s.to_owned()),
                    tag(": "),
                    separated_list1(space1, map(alpha1, |s: &str| s.to_owned())),
                ),
            ),
            |vertices| {
                let mut vertex_id_mapping = BTreeMap::new();
                let mut wires = Vec::new();

                for (from, tos) in vertices {
                    let from_id = vertex_id_mapping
                        .entry(from)
                        .or_insert_with(|| {
                            let new_id = VertexId(wires.len());
                            wires.push(Vec::new());
                            new_id
                        })
                        .clone();
                    for to in tos {
                        let to_id = vertex_id_mapping
                            .entry(to)
                            .or_insert_with(|| {
                                let new_id = VertexId(wires.len());
                                wires.push(Vec::new());
                                new_id
                            })
                            .clone();
                        wires[from_id.0].push(to_id);
                        wires[to_id.0].push(from_id);
                    }
                }
                Circuit { wires }
            },
        )(input)
    }

    fn find_non_zero_three_cut_partition_sizes(&self) -> (usize, usize) {
        let cut1s = self.edges_to_traverse_everything([]);
        for (cut1i, cut1) in cut1s.iter().enumerate() {
            let cut2s = self.edges_to_traverse_everything([cut1.clone()]);
            for (cut2i, cut2) in cut2s.iter().enumerate() {
                if cut1s[0..cut1i].contains(&cut2) {
                    continue;
                }
                for cut3 in self.edges_to_traverse_everything([cut1.clone(), cut2.clone()]) {
                    if cut1s[0..cut1i].contains(&cut3) || cut2s[0..cut2i].contains(&cut3) {
                        // if (cut2, *) didn't work, then (*, cut2) also wouldn't work.
                        continue;
                    }
                    let (size1, size2) = self.partition_sizes([cut1.clone(), cut2.clone(), cut3]);
                    if size2 > 0 {
                        return (size1, size2);
                    }
                }
            }
        }
        panic!("No partitions with three cuts");
    }

    fn partition_sizes(&self, cuts: [Edge; 3]) -> (usize, usize) {
        let mut visited = vec![false; self.wires.len()];
        let mut frontier = Vec::new();

        visited[0] = true;
        frontier.push(VertexId(0));
        let mut visited_count = 1;

        while let Some(from) = frontier.pop() {
            for to in &self.wires[from.0] {
                let edge = Edge::new(from, *to);
                if !cuts.contains(&edge) && !visited[to.0] {
                    visited[to.0] = true;
                    visited_count += 1;
                    frontier.push(*to);
                }
            }
        }

        (visited_count, self.wires.len() - visited_count)
    }

    fn edges_to_traverse_everything<const N: usize>(&self, cuts: [Edge; N]) -> Vec<Edge> {
        let mut visited = vec![false; self.wires.len()];
        let mut frontier = Vec::new();

        visited[0] = true;
        frontier.push(VertexId(0));
        let mut used_edges = Vec::new();

        while let Some(from) = frontier.pop() {
            for to in &self.wires[from.0] {
                let edge = Edge::new(from, *to);
                if !cuts.contains(&edge) && !visited[to.0] {
                    visited[to.0] = true;
                    used_edges.push(edge);
                    frontier.push(*to);
                }
            }
        }
        used_edges
    }
}

impl Edge {
    fn new(a: VertexId, b: VertexId) -> Edge {
        Edge { a, b }
    }
}