Skip to content

Commit 25b308f

Browse files
authored
add greedy algorithms example in rust (#295)
1 parent 93a7b22 commit 25b308f

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

10_greedy_algorithms/rust/Cargo.lock

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

10_greedy_algorithms/rust/Cargo.toml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[package]
2+
name = "greedy_algorithms"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[dependencies]

10_greedy_algorithms/rust/src/main.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
use std::collections::{HashMap, HashSet};
2+
3+
fn main() {
4+
let mut states_needed = HashSet::from(["mt", "wa", "or", "id", "nv", "ut", "ca", "az"]);
5+
6+
let mut stations = HashMap::from([
7+
("kone", HashSet::from(["id", "nv", "ut"])),
8+
("ktwo", HashSet::from(["wa", "id", "mt"])),
9+
("kthree", HashSet::from(["or", "nv", "ca"])),
10+
("kfour", HashSet::from(["nv", "ut"])),
11+
("kfive", HashSet::from(["ca", "az"])),
12+
]);
13+
14+
let mut final_stations = HashSet::new();
15+
while !states_needed.is_empty() {
16+
let mut best_station = None;
17+
let mut states_covered = HashSet::new();
18+
for (station, states_for_station) in &stations {
19+
let covered: HashSet<_> = states_needed
20+
.intersection(&states_for_station)
21+
.cloned()
22+
.collect();
23+
if covered.len() > states_covered.len() && !final_stations.contains(station) {
24+
best_station = Some(*station);
25+
states_covered = covered;
26+
}
27+
}
28+
match best_station {
29+
Some(station) => {
30+
states_needed = states_needed.difference(&states_covered).cloned().collect();
31+
final_stations.insert(station);
32+
stations.remove(station);
33+
}
34+
None => {
35+
println!("Coold not complete: {:?}", final_stations);
36+
break;
37+
}
38+
}
39+
}
40+
41+
println!("{:?}", final_stations);
42+
}

0 commit comments

Comments
 (0)