-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday25.rs
148 lines (123 loc) · 2.77 KB
/
day25.rs
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 crate::solutions::year2024::day25::LockAndKey::{Key, Lock};
use crate::solutions::Solution;
use crate::utils::grid::Grid;
use std::str::FromStr;
const MAX_HEIGHT: u8 = 6;
pub struct Day25;
impl Solution for Day25 {
fn part_one(&self, input: &str) -> String {
let items: Vec<LockAndKey> = input
.split_terminator("\n\n")
.map(|item| item.parse().unwrap())
.collect();
let locks = Self::filter_items(&items, |item| matches!(item, Lock(_)));
let keys = Self::filter_items(&items, |item| matches!(item, Key(_)));
let mut overlap_count = 0;
for lock in &locks {
for key in &keys {
if key.overlaps(lock) {
overlap_count += 1;
}
}
}
overlap_count.to_string()
}
fn part_two(&self, _input: &str) -> String {
String::from("0")
}
}
impl Day25 {
fn filter_items(items: &[LockAndKey], item_type: fn(&LockAndKey) -> bool) -> Vec<&LockAndKey> {
items.iter().filter(|item| item_type(item)).collect()
}
}
#[derive(Debug)]
struct Pins(Vec<u8>);
#[derive(Debug)]
enum LockAndKey {
Lock(Pins),
Key(Pins),
}
impl LockAndKey {
fn overlaps(&self, other: &Self) -> bool {
if !(matches!(self, Key(_)) && matches!(other, Lock(_))
|| matches!(self, Lock(_)) && matches!(other, Key(_)))
{
unreachable!()
}
let self_pins = self.pins();
let other_pins = other.pins();
for i in 0..self_pins.0.len() {
if self_pins.0[i] + other_pins.0[i] >= MAX_HEIGHT {
return false;
}
}
true
}
fn pins(&self) -> &Pins {
match self {
Lock(pins) => pins,
Key(pins) => pins,
}
}
}
impl FromStr for LockAndKey {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
let grid: Grid<char> = Grid::from(s);
let pins: Vec<u8> = grid
.columns()
.values()
.map(|c| (c.iter().filter(|(_, char)| **char == &'#').count() - 1) as u8)
.collect();
Ok(match grid.top_left_corner_element().unwrap() {
'#' => Lock(Pins(pins)),
'.' => Key(Pins(pins)),
_ => unreachable!(),
})
}
}
#[cfg(test)]
mod tests {
use crate::solutions::year2024::day25::Day25;
use crate::solutions::Solution;
const EXAMPLE: &str = r#"#####
.####
.####
.####
.#.#.
.#...
.....
#####
##.##
.#.##
...##
...#.
...#.
.....
.....
#....
#....
#...#
#.#.#
#.###
#####
.....
.....
#.#..
###..
###.#
###.#
#####
.....
.....
.....
#....
#.#..
#.#.#
#####"#;
#[test]
fn part_one_example() {
assert_eq!("3", Day25.part_one(EXAMPLE));
}
}