-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rs
90 lines (73 loc) · 2.49 KB
/
main.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
use std::collections::HashSet;
use std::fs;
fn main() {
let contents = fs::read_to_string("input.txt").unwrap();
let containers: Vec<u8> = contents.lines().map(|x| x.parse::<u8>().unwrap()).collect();
println!("{:?}", containers);
// One combination of container will be represented as a u32
// We'll use the bits to check if a container is used or not
let mut seen_comb: HashSet<u32> = HashSet::new();
let combinations = fit_eggnog(150, &containers, 0, &mut seen_comb);
let min_containers = combinations
.iter()
.map(|comb| count_containers(*comb))
.min()
.unwrap();
let count_min_containers: u32 = combinations
.iter()
.map(|comb| {
if count_containers(*comb) == min_containers {
return 1;
} else {
return 0;
}
})
.sum();
println!("Nbr of combinations: {}", combinations.len());
println!("Min containers: {}", min_containers);
println!("Nbr of min containers: {}", count_min_containers);
}
fn fit_eggnog(
eggnog_to_fit: u8,
containers: &Vec<u8>,
cur_comb: u32,
seen_comb: &mut HashSet<u32>,
) -> HashSet<u32> {
let mut combinations: HashSet<u32> = HashSet::new();
if eggnog_to_fit == 0 {
// println!("{:?}", cur_comb);
combinations.insert(cur_comb);
return combinations;
}
for (idx, capacity) in containers.iter().enumerate() {
// Prepare a mask for the container at this index
let mask = 1 << idx;
// Check if the container at this index is already used before proceeding
if (cur_comb & mask) == 0 && *capacity <= eggnog_to_fit {
// Flip the bit at the index matching the current container
let temp_cur_comb = cur_comb | mask;
// Check if this combination was seen before. If it was, skip it since it has already been explored
if seen_comb.contains(&temp_cur_comb) {
continue;
} else {
seen_comb.insert(temp_cur_comb);
}
combinations.extend(fit_eggnog(
eggnog_to_fit - capacity,
containers,
temp_cur_comb,
seen_comb,
));
}
}
return combinations;
}
fn count_containers(combination: u32) -> u8 {
let mut total: u8 = 0;
for idx in 0..32 {
if (combination & (1 << idx)) != 0 {
total += 1;
};
}
return total;
}