Introduction
You work for a company that sells fonts through their website.
They’d like to show a different sentence each time someone views a font on their website.
To give a comprehensive sense of the font, the random sentences should use all the letters in the English alphabet.
They’re running a competition to get suggestions for sentences that they can use.
You’re in charge of checking the submissions to see if they are valid.
Pangram comes from Greek, παν γράμμα, pan gramma, which means "every letter".
The best known English pangram is:
> The quick brown fox jumps over the lazy dog.
Instructions
Instructions
Your task is to figure out if a sentence is a pangram.
A pangram is a sentence using every letter of the alphabet at least once.
It is case insensitive, so it doesn’t matter if a letter is lower-case (e.g. k) or upper-case (e.g. K).
For this exercise, a sentence is a pangram if it contains each of the 26 letters in the English alphabet.
Dig Deeper
all with contains on lower case
all with contains on lowercased letters
pub fn is_pangram(sentence: &str) -> bool {
let sentence_lowered = sentence.to_lowercase();
('a'..='z').all(|ltr| sentence_lowered.contains(ltr))
}
- This begins by lowercasing the input by using to_lowercase.
- It then checks if all letters in the alphabet are contained in the
sentence,
using the Iterator method all with the str method contains.
If all of the letters in the alphabet are contained in the sentence, then the function will return true.
HashSet with is_subset
HashSet with is_subset
use std::collections::HashSet;
pub fn is_pangram(sentence: &str) -> bool {
let all: HashSet<char> = HashSet::from_iter("abcdefghijklmnopqrstuvwxyz".chars());
let used: HashSet<char> = HashSet::from_iter(sentence.to_lowercase().chars());
all.is_subset(&used)
}
In this approach a HashSet is made of the lowercase alphabet chars using the from_iter method,
and another HashSet is made from the to_lowercase sentence chars.
The function returns if the alphabet HashSet is_subset of the sentence HashSet.
If all of the letters in the alphabet are a subset of the letters in the sentence,
then is_subset will return true.
HashSet with len
HashSet with len
use std::collections::HashSet;
pub fn is_pangram(sentence: &str) -> bool {
sentence
.to_lowercase()
.chars()
.filter(|c| c.is_ascii_alphabetic())
.collect::<HashSet<char>>()
.len()
== 26
}
This approach chains several functions together to determine the result.
- It first passes the
sentence to_lowercase.
- The lowercased
sentence is then iterated by chars.
- The
chars are filtered in its closure so that only a character that is_ascii_alphabetic
makes it through to be collected into a HashSet.
- The function returns if the len of the
HashSet is 26.
If the number of unique letters in the HashSet is equal to the 26 letters in the alphabet, then the function will return true.
Source: Exercism rust/pangram