Created
September 28, 2020 13:28
-
-
Save jamesmcm/8d039afb95214eaa7e9c6827502a16da to your computer and use it in GitHub Desktop.
Minimum needed characters problem solved in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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