Programming Problem: Pangram
Article #9 in a 9-part series.
- 1 - Programming Problem: Determine if Two Strings Are Anagrams
- 2 - Programming Problem: Sum-Zero Triplet
- 3 - Programming Problem: Palindromes
- 4 - Problem: Validate a Phone Number
- 5 - Programming Problem: Single-Edit Difference
- 6 - Prime Factors Problem 1: LCM
- 7 - Prime Factors Problem 2: Largest Prime Factor
- 8 - How-To: Substrings in Swift
- 9 - this article
Goal: write a method to determine if a string is a pangram.
observations
A pangram is a phrase using all the letters of the alphabet.
- The quick brown fox jumps over the lazy dog.
- The five boxing wizards jump quickly.
- Bright vixens jump; dozy fowl quack.
assumptions
For this problem let the alphabet consist of only letters ignoring case, and let’s assume our input may include punctuation, digits, or spaces.
program
Give it a try in your programming language of choice, and try to be brief. Test negative case by removing words from the pangram. Below I share my solutions in Swift and C#.
my solution examples
A pangram uses all letter characters at least once. Counting would be one option, but notice we’re looking for a phrase that is the superset of the alphabet.
Swift 3
Turn the phrase into a Set and find if the phrase-set is a superset of the letters-set.
//: Playground - noun: a place where people can play
import Cocoa
let letters = "abcdefghijklmnopqrstuvwxyz"
let phrase = "The quick brown fox jumps over Lazy Dog."
let phraseFail = "The brown fox jumps over the lazy dog."
let letterSet = Set(letters)
let phraseSet = Set(phrase.lowercased()
let phraseFailSet = Set(phraseFail.lowercased()
if phraseSet.isSuperset(of: letterSet) {
print("is pangram")
}
else {
print("Not pangram")
}
if phraseFailSet.isSuperset(of: letterSet) {
print("is pangram")
}
else {
print("Not pangram")
}
C#
For this solution I used LINQ to query distinct letters which should equal the length of our English alphabet, 26. Learn more about LINQ on MSDN.
using System;
using System.Linq;
namespace MyTutorialConsoleApp
{
public static class StringPlay
{
public static bool IsPangram(string phrase)
{
if (String.IsNullOrWhiteSpace(phrase) || phrase.Length < 26)
{
return false;
}
if (phrase.Where(char.IsLetter).Select(char.ToLower).Distinct().Count() == 26)
{
return true;
}
return false;
}
}
}
Article #9 in a 9-part series.
- 1 - Programming Problem: Determine if Two Strings Are Anagrams
- 2 - Programming Problem: Sum-Zero Triplet
- 3 - Programming Problem: Palindromes
- 4 - Problem: Validate a Phone Number
- 5 - Programming Problem: Single-Edit Difference
- 6 - Prime Factors Problem 1: LCM
- 7 - Prime Factors Problem 2: Largest Prime Factor
- 8 - How-To: Substrings in Swift
- 9 - this article