add greedy algorithms example in rust (#295)

This commit is contained in:
Artem Chernyak
2024-12-07 07:37:26 -06:00
committed by GitHub
parent 93a7b227b3
commit 25b308ff5f
3 changed files with 55 additions and 0 deletions

7
10_greedy_algorithms/rust/Cargo.lock generated Normal file
View File

@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "greedy_algorithms"
version = "0.1.0"

View File

@@ -0,0 +1,6 @@
[package]
name = "greedy_algorithms"
version = "0.1.0"
edition = "2021"
[dependencies]

View File

@@ -0,0 +1,42 @@
use std::collections::{HashMap, HashSet};
fn main() {
let mut states_needed = HashSet::from(["mt", "wa", "or", "id", "nv", "ut", "ca", "az"]);
let mut stations = HashMap::from([
("kone", HashSet::from(["id", "nv", "ut"])),
("ktwo", HashSet::from(["wa", "id", "mt"])),
("kthree", HashSet::from(["or", "nv", "ca"])),
("kfour", HashSet::from(["nv", "ut"])),
("kfive", HashSet::from(["ca", "az"])),
]);
let mut final_stations = HashSet::new();
while !states_needed.is_empty() {
let mut best_station = None;
let mut states_covered = HashSet::new();
for (station, states_for_station) in &stations {
let covered: HashSet<_> = states_needed
.intersection(&states_for_station)
.cloned()
.collect();
if covered.len() > states_covered.len() && !final_stations.contains(station) {
best_station = Some(*station);
states_covered = covered;
}
}
match best_station {
Some(station) => {
states_needed = states_needed.difference(&states_covered).cloned().collect();
final_stations.insert(station);
stations.remove(station);
}
None => {
println!("Coold not complete: {:?}", final_stations);
break;
}
}
}
println!("{:?}", final_stations);
}