Reputation: 162
use itertools::Itertools;
fn shifter(s: &str) -> usize {
s.split(' ')
.unique()
.map(|x| x.chars().
}
Im trying to finish up the task to calculate how many "shifter words" a given &str contains without any duplicates. "shifter word" is one that consist only of "H", "I", "N", "O", "S", "X", "Z", "M" and "W".
shifter("SOS IN THE HOME") == 2 // shifter words are "SOS" and "IN"
shifter("WHO IS SHIFTER AND WHO IS NO") == 3 // shifter words are "WHO", "IS", "NO"
shifter("TASK") == 0 // no shifter words
shifter("") == 0 // no shifter words in empty string
Upvotes: 1
Views: 1050
Reputation: 60051
Putting it all together from:
fn shifter(s: &str) -> usize {
s.split(' ')
.unique()
.filter(|x| !x.is_empty() && x.chars().all(|c| "HINOSXZMW".contains(c)))
.count()
}
The is_empty()
is there because all()
returns true for an empty collection.
See it working on the playground.
Upvotes: 3
Reputation: 5545
You can test if every element matches a given predicate by using Iterator::all()
and str::contains
.
"SOS".chars().all(|c| "HINOSXZMW".contains(c)); // true
Note that there's also slice::contains
, so the following would work as well:
let letters = ['H', 'I', 'N', 'O', 'S', 'X', 'Z', 'M', 'W'];
"SOS".chars().all(|c| letters.contains(&c)); // true
Upvotes: 4