Skip to content

Instantly share code, notes, and snippets.

@jamesmcm
Created September 28, 2020 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesmcm/8d039afb95214eaa7e9c6827502a16da to your computer and use it in GitHub Desktop.
Save jamesmcm/8d039afb95214eaa7e9c6827502a16da to your computer and use it in GitHub Desktop.
Minimum needed characters problem solved in Rust
use std::collections::HashMap;
fn main() {
println!("{:?}", word2chars("pear"));
println!("{:?}", needed_chars(&["apple", "pear"]));
}
fn needed_chars(words: &[&str]) -> HashMap<char, u32> {
words
.iter()
.map(|x| word2chars(x))
.fold(HashMap::new(), |mut x, y| {
for (k, v) in y {
x.entry(k).and_modify(|z| *z = (*z).max(v)).or_insert(v);
}
x
})
}
fn word2chars(word: &str) -> HashMap<char, u32> {
word.chars().fold(HashMap::<char, u32>::new(), |mut x, y| {
x.entry(y).and_modify(|z| *z += 1).or_insert(1);
x
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment