-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday19.rs
More file actions
57 lines (42 loc) · 1.23 KB
/
Copy pathday19.rs
File metadata and controls
57 lines (42 loc) · 1.23 KB
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
//! Linen Layout
//!
//! Summary:
use std::collections::HashMap;
pub fn parse(input: &str) -> &str {
input
}
pub fn part1(input: &str) -> usize {
solve(input, false)
}
pub fn part2(input: &str) -> usize {
solve(input, true)
}
fn solve(input: &str, part2: bool) -> usize {
let (item_list, design_list) = input.split_once("\n\n").unwrap();
let items = item_list.split(", ").collect::<Vec<_>>();
let designs = design_list.trim().split("\n").collect::<Vec<_>>();
let mut seen: HashMap<String, usize> = HashMap::new();
let (ans1, ans2) = designs.iter().fold((0, 0), |acc, design| {
let sol = check(design.to_string(), &items, &mut seen);
(acc.0 + (sol > 0) as usize, acc.1 + sol)
});
if part2 {
return ans2;
}
ans1
}
fn check(receipt: String, items: &Vec<&str>, seen: &mut HashMap<String, usize>) -> usize {
if receipt.is_empty() {
return 1;
};
if seen.contains_key(&receipt) {
return *seen.get(&receipt).unwrap();
}
let solutions = items
.iter()
.filter(|v| receipt.starts_with(**v))
.map(|v| check(receipt.clone().split_off(v.len()), items, seen))
.sum();
seen.insert(receipt, solutions);
solutions
}