Pangram checker

From Rosetta Code

Jump to: navigation, search
Task
Pangram checker
You are encouraged to solve this task according to the task description, using any language you may know.

Write a function or method to check a sentence to see if it is a pangram or not and show its use.

A pangram is a sentence that contains all the letters of the English alphabet at least once, for example: The quick brown fox jumps over the lazy dog.

Contents

[edit] Ada

Using Sets

 
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Maps; use Ada.Strings.Maps;
with Ada.Characters.Handling; use Ada.Characters.Handling;
procedure pangram is
 
function ispangram(txt: String) return Boolean is
lowtxt : String := To_Lower(txt);
letset,txtset : Character_Set;
begin
letset := To_Set("abcdefghijklmnopqrstuvwxyz");
txtset := To_Set(lowtxt);
return (letset-txtset)=Null_Set;
end ispangram;
 
begin
put_line(Boolean'Image(ispangram("This is a test")));
put_line(Boolean'Image(ispangram("The quick brown fox jumps over the lazy dog")));
put_line(Boolean'Image(ispangram("NOPQRSTUVWXYZ abcdefghijklm")));
put_line(Boolean'Image(ispangram("abcdefghijklopqrstuvwxyz"))); --Missing m, n
end pangram;
 

Output:

FALSE
TRUE
TRUE
FALSE

[edit] ALGOL 68

Works with: ALGOL 68 version Standard - no extensions to language used

Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny

Works with: ELLA ALGOL 68 version Any (with appropriate job cards)

# init pangram: #
INT la = ABS "a", lz = ABS "z";
INT ua = ABS "A", uz = ABS "Z";
IF lz-la+1 > bits width THEN
put(stand error, "Exception: insufficient bits in word for task");
stop
FI;
 
PROC is a pangram = (STRING test)BOOL: (
BITS a2z := BIN(ABS(2r1 SHL (lz-la))-1); # assume: ASCII & Binary #
FOR i TO UPB test WHILE
INT c = ABS test[i];
IF la <= c AND c <= lz THEN
a2z := a2z AND NOT(2r1 SHL (c-la))
ELIF ua <= c AND c <= uz THEN
a2z := a2z AND NOT(2r1 SHL (c-ua))
FI;
# WHILE # a2z /= 2r0 DO
SKIP
OD;
a2z = 2r0
);
 
main:(
[]STRING test list = (
"Big fjiords vex quick waltz nymph",
"The quick brown fox jumps over a lazy dog",
"A quick brown fox jumps over a lazy dog"
);
FOR key TO UPB test list DO
STRING test = test list[key];
IF is a pangram(test) THEN
print(("""",test,""" is a pangram!", new line))
FI
OD
)

Output:

"Big fjiords vex quick waltz nymph" is a pangram!
"The quick brown fox jumps over a lazy dog" is a pangram!

[edit] AutoHotkey

Gui, -MinimizeBox
Gui, Add, Edit, w300 r5 vText
Gui, Add, Button, x105 w100 Default, Check Pangram
Gui, Show,, Pangram Checker
Return
 
GuiClose:
ExitApp
Return
 
ButtonCheckPangram:
Gui, Submit, NoHide
Loop, 26
If Not InStr(Text, Char := Chr(64 + A_Index)) {
MsgBox,, Pangram, Character %Char% is missing!
Return
}
MsgBox,, Pangram, OK`, this is a Pangram!
Return

[edit] BASIC

Works with: QBasic

DECLARE FUNCTION IsPangram! (sentence AS STRING)
 
DIM x AS STRING
 
x = "My dog has fleas."
GOSUB doIt
x = "The lazy dog jumps over the quick brown fox."
GOSUB doIt
x = "Jackdaws love my big sphinx of quartz."
GOSUB doIt
x = "What's a jackdaw?"
GOSUB doIt
 
END
 
doIt:
PRINT IsPangram!(x), x
RETURN
 
FUNCTION IsPangram! (sentence AS STRING)
'returns -1 (true) if sentence is a pangram, 0 (false) otherwise
DIM l AS INTEGER, s AS STRING, t AS INTEGER
DIM letters(25) AS INTEGER
 
FOR l = 1 TO LEN(sentence)
s = UCASE$(MID$(sentence, l, 1))
SELECT CASE s
CASE "A" TO "Z"
t = ASC(s) - 65
letters(t) = 1
END SELECT
NEXT
 
FOR l = 0 TO 25
IF letters(l) < 1 THEN
IsPangram! = 0
EXIT FUNCTION
END IF
NEXT
 
IsPangram! = -1
END FUNCTION

Output:

 0            My dog has fleas.
-1            The quick brown fox jumps over the lazy dog.
-1            Jackdaws love my big sphinx of quartz.
 0            What's a jackdaw?

[edit] C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int isPangram( char *string )
{
static char *alphabet="abcdefghijklmnopqrstuvwxyz";
char wasused[26], *sp, *ap;
int j;
 
for (j=0; j<26; j++) wasused[j]=0;
for (sp=string;*sp; sp++) {
ap = strchr(alphabet, tolower(*sp));
if (ap != NULL) {
wasused[ap-alphabet] = 1;
}
}
for (j=0; (j<26) && wasused[j]; j++);
// if (j<26) printf("Missing character %c\n", alphabet[j]);
return (j==26);
}
 
main( int argc, char *argv[])
{
char *pangramTxt;
if (argc < 2) {
printf("usage %s (text to check for pangram)\n", argv[0]);
exit(1);
}
pangramTxt = argv[1];
printf("%s\n",pangramTxt);
printf("Is pangram? %s\n", (isPangram(pangramTxt)?"Yes":"No"));
return 0;
}

Usage:

>pangram "The quick brown fox jumps over lazy dogs."
Is Pangram? Yes

[edit] C++

#include <algorithm>
#include <cctype>
#include <string>
using namespace std;
 
const string kAlphabet("abcdefghijklmnopqrstuvwxyz");
 
bool is_pangram(string s) {
// Convert to lower case.
transform(s.begin(), s.end(), s.begin(), (int(*)(int))tolower);
// Convert to a sorted sequence of unique characters.
sort(s.begin(), s.end());
s.erase(
unique(s.begin(), s.end()),
s.end());
// Remove non-alphabetic characters.
s.erase(
set_intersection(
s.begin(), s.end(),
kAlphabet.begin(), kAlphabet.end(),
s.begin()),
s.end());
// For a pangram, we're left with a..z.
return s == kAlphabet;
}

[edit] C#

using System;
using System.Linq;
 
class Program
{
public static string alphabet = "abcdefghijklmnopqrstuvwxyz";
 
static bool CheckPangram(string str)
{
var chars = str.ToLower().ToList();
 
return alphabet.ToList().All(x => chars.Contains(x));
}
 
static void Main(string[] args)
{
Console.WriteLine(CheckPangram("the quick brown fox jumps over the lazy dog"));
Console.WriteLine(CheckPangram("this is not a pangram"));
}
}

[edit] Common Lisp

(defun pangramp (s)
(null (set-difference
(loop for c from (char-code #\A) upto (char-code #\Z) collect (code-char c))
(coerce (string-upcase s) 'list))))

[edit] D

There are several ways to write this function, this is a low-level one.

/*pure*/ nothrow bool isPangram(string txt) {
pure nothrow static uint fullBitSet() { // compile-time function
uint result;
foreach (c; "abcdefghijklmnopqrstuvwxyz")
result |= (1u << (c - 'a'));
return result;
}
enum uint FULL_BIT_SET = fullBitSet(); // 67_108_863;
 
uint charset;
 
foreach (c; txt) {
if (c >= 'a' && c <= 'z')
charset |= (1u << (c - 'a'));
else if (c >= 'A' && c <= 'Z')
charset |= (1u << (c - 'A'));
}
 
return charset == FULL_BIT_SET;
}
 
void main() {
assert(isPangram("the quick brown fox jumps over the lazy dog")); // true
assert(!isPangram("the quick brown fox jumped over the lazy dog")); // false, no s
assert(isPangram("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); // true
assert(!isPangram("ABCDEFGHIJKLMNOPQSTUVWXYZ")); // false, no r
assert(!isPangram("ABCDEFGHIJKL.NOPQRSTUVWXYZ")); // false, no m
assert(isPangram("ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ")); // true
assert(!isPangram("")); // false
}

[edit] Clojure

(defn pangram? [s]
(let [letters (into #{} "abcdefghijklmnopqrstuvwxyz")]
(= (->> s .toLowerCase (filter letters) (into #{})) letters)))

[edit] E

def isPangram(sentence :String) {
return ("abcdefghijklmnopqrstuvwxyz".asSet() &! sentence.toLowerCase().asSet()).size() == 0
}

&! is the “but-not” or set difference operator.

[edit] F#

If the difference between the set of letters in the alphabet and the set of letters in the given string (after conversion to lower case) is the empty set then every letter appears somewhere in the given string:

let isPangram (str: string) = (set['a'..'z'] - set(str.ToLower())).IsEmpty

[edit] Factor

Translation of: E

: pangram? ( str -- ? )
[ "abcdefghijklmnopqrstuvwxyz" ] dip >lower diff length 0 = ;
 
"How razorback-jumping frogs can level six piqued gymnasts!" pangram? .

[edit] Forth

: pangram? ( addr len -- ? )
0 -rot bounds do
i c@ 32 or [char] a -
dup 0 26 within if
1 swap lshift or
else drop then
loop
1 26 lshift 1- = ;
 
s" The five boxing wizards jump quickly." pangram? . \ -1

[edit] Fortran

Works with: Fortran version 90 and later

module pangram
 
implicit none
private
public :: is_pangram
character (*), parameter :: lower_case = 'abcdefghijklmnopqrstuvwxyz'
character (*), parameter :: upper_case = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
 
contains
 
function to_lower_case (input) result (output)
 
implicit none
character (*), intent (in) :: input
character (len (input)) :: output
integer :: i
integer :: j
 
output = input
do i = 1, len (output)
j = index (upper_case, output (i : i))
if (j /= 0) then
output (i : i) = lower_case (j : j)
end if
end do
 
end function to_lower_case
 
function is_pangram (input) result (output)
 
implicit none
character (*), intent (in) :: input
character (len (input)) :: lower_case_input
logical :: output
integer :: i
 
lower_case_input = to_lower_case (input)
output = .true.
do i = 1, len (lower_case)
if (index (lower_case_input, lower_case (i : i)) == 0) then
output = .false.
exit
end if
end do
 
end function is_pangram
 
end module pangram

Example:

program test
 
use pangram, only: is_pangram
 
implicit none
character (256) :: string
 
string = 'This is a sentence.'
write (*, '(a)') trim (string)
write (*, '(l1)') is_pangram (string)
string = 'The five boxing wizards jumped quickly.'
write (*, '(a)') trim (string)
write (*, '(l1)') is_pangram (string)
 
end program test

Output:

This is a sentence.
F
The five boxing wizards jumped quickly.
T

[edit] Haskell

import Data.Char (toLower)
import Data.List ((\\))
 
pangram :: String -> Bool
pangram = null . (['a' .. 'z'] \\) . map toLower
 
main = print $ pangram "How razorback-jumping frogs can level six piqued gymnasts!"

[edit] Icon and Unicon

[edit] Icon

A panagram procedure:

procedure panagram(s)     #: return s if s is a panagram and fail otherwise
if (map(s) ** &lcase) === &lcase then return s
end

And a main to drive it:

procedure main(arglist)
 
if *arglist > 0 then
every ( s := "" ) ||:= !arglist || " "
else
s := "The quick brown fox jumps over the lazy dog."
 
writes(image(s), " -- is")
writes(if not panagram(s) then "n't")
write(" a panagram.")
end

[edit] Unicon

This Icon solution works in Unicon.

[edit] Ioke

Text isPangram? = method(
letters = "abcdefghijklmnopqrstuvwxyz" chars
text = self lower chars
letters map(x, text include?(x)) reduce(&&)
)

Here is an example of it's use in the Ioke REPL:

 
iik> "The quick brown fox jumps over the lazy dog" isPangram?
"The quick brown fox jumps over the lazy dog" isPangram?
+> true
 
iik> "The quick brown fox jumps over the" isPangram?
"The quick brown fox jumps over the" isPangram?
+> false

[edit] J

Solution:

require 'strings'
isPangram=: (a. {~ 97+i.26) */@e. tolower

Example use:

   isPangram 'The quick brown fox jumps over the lazy dog.'
1
isPangram 'The quick brown fox falls over the lazy dog.'
0

[edit] Java

Works with: Java version 1.5+

public class Pangram {
public static boolean isPangram(String test){
boolean pangram = true;
String lcTest = test.toLowerCase();
for(char a = 'a'; a <= 'z'; a++){
pangram &= lcTest.contains("" + a);
}
return pangram;
}
 
public static void main(String[] args){
System.out.println(isPangram("the quick brown fox jumps over the lazy dog"));//true
System.out.println(isPangram("the quick brown fox jumped over the lazy dog"));//false, no s
System.out.println(isPangram("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));//true
System.out.println(isPangram("ABCDEFGHIJKLMNOPQSTUVWXYZ"));//false, no r
System.out.println(isPangram("ABCDEFGHIJKL.NOPQRSTUVWXYZ"));//false, no m
System.out.println(isPangram("ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ"));//true
System.out.println(isPangram(""));//false
}
}

Output:

true
false
true
false
false
true
false

[edit] JavaScript

Translation of: Java

function is_pangram(str) {
var s = str.toLowerCase();
// sorted by frequency ascending (http://en.wikipedia.org/wiki/Letter_frequency)
var letters = "zqxjkvbpygfwmucldrhsnioate";
for (var i = 0; i < 26; i++)
if (s.indexOf(letters.charAt(i)) == -1)
return false;
return true;
}
 
print(is_pangram("is this a pangram")); // false
print(is_pangram("The quick brown fox jumps over the lazy dog")); // true

[edit] Logo

to remove.all :s :set
if empty? :s [output :set]
if word? :s [output remove.all butfirst :s remove first :s :set]
output remove.all butfirst :s remove.all first :s :set
end
to pangram? :s
output empty? remove.all :s "abcdefghijklmnopqrstuvwxyz
end
 
show pangram? [The five boxing wizards jump quickly.]  ; true

[edit] Lua

require"lpeg"
S, C = lpeg.S, lpeg.C
function ispangram(s)
return #(C(S(s)^0):match"abcdefghijklmnopqrstuvwxyz") == 26
end
 
print(ispangram"waltz, bad nymph, for quick jigs vex")
print(ispangram"bobby")
print(ispangram"long sentence")

[edit] MATLAB

function trueFalse = isPangram(string)
 
%This works by histogramming the ascii character codes for lower case
%letters contained in the string (which is first converted to all
%lower case letters). Then it finds the index of the first letter that
%is not contained in the string (this is faster than using the find
%without the second parameter). If the find returns an empty array then
%the original string is a pangram, if not then it isn't.
 
trueFalse = isempty(find( histc(lower(string),(97:122))==0,1 ));
 
end

Sample Output:

isPangram('The quick brown fox jumps over the lazy dog.')
 
ans =
 
1

[edit] OCaml

let pangram str =
let ar = Array.make 26 false in
String.iter (function
| 'a'..'z' as c -> ar.(Char.code c - Char.code 'a') <- true
| _ -> ()
) (String.lowercase str);
Array.fold_left ( && ) true ar
let check str =
Printf.printf " %b -- %s\n" (pangram str) str
 
let () =
check "this is a sentence";
check "The quick brown fox jumps over the lazy dog.";
;;

outputs:

false -- this is a sentence
true -- The quick brown fox jumps over the lazy dog.

[edit] Oz

declare
fun {IsPangram Xs}
{List.sub
{List.number &a &z 1}
{Sort {Map Xs Char.toLower} Value.'<'}}
end
in
{Show {IsPangram "The quick brown fox jumps over the lazy dog."}}

[edit] Perl

use List::MoreUtils 'all';
 
sub pangram {all {$_[0] =~ /$_/i} 'a' .. 'z';}
 
print "Yes.\n" if pangram 'Cozy lummox gives smart squid who asks for job pen.';

[edit] Perl 6

sub pangram($s) {
Set.new("a".."z").subsetorequal($s.comb);
}

[edit] PicoLisp

(de isPangram (Str)
(not
(diff
'`(chop "abcdefghijklmnopqrstuvwxyz")
(chop (lowc Str)) ) ) )

[edit] PHP

function pangram($str){
$alphabet = Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
foreach($alphabet as $val){
if(stripos($str,$val) === false){
return false;
}
}
return true;
}
 
echo pangram("The quick brown fox jumps over the lazy dog"); // 1
echo pangram("Am I a pangram?"); // 0

[edit] PL/I

 
test_pangram: procedure options (main);
 
is_pangram: procedure() returns (bit(1) aligned);
 
declare text character (200) varying;
declare c character (1);
 
get edit (text) (L);
put skip list (text);
 
text = lowercase(text);
 
do c = 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z';
if index(text, c) = 0 then return ('0'b);
end;
return ('1'b);
end is_pangram;
 
put skip list ('Please type a sentence');
 
if is_pangram() then
put skip list ('The sentence is a pangram.');
else
put skip list ('The sentence is not a pangram.');
 
end test_pangram;
 

Output:

 
Please type a sentence
 
the quick brown fox jumps over the lazy dog
The sentence is a pangram.
 

[edit] Prolog

Works with SWI-Prolog

pangram(L) :-
numlist(0'a, 0'z, Alphabet),
forall(member(C, Alphabet), member(C, L)).
 
pangram_example :-
L1 = "the quick brown fox jumps over the lazy dog",
( pangram(L1) -> R1= ok; R1 = ko),
format('~s --> ~w ~n', [L1,R1]),
 
L2 = "the quick brown fox jumped over the lazy dog",
( pangram(L2) -> R2 = ok; R2 = ko),
format('~s --> ~w ~n', [L2, R2]).
 

output

?- pangram_example.
the quick brown fox jumps over the lazy dog --> ok
the quick brown fox jumped over the lazy dog --> ko
true.

[edit] PureBasic

Procedure IsPangram_fast(String$)
String$ = LCase(string$)
char_a=Asc("a")
; sets bits in a variable if a letter is found, reads string only once
For a = 1 To Len(string$)
char$ = Mid(String$, a, 1)
pos = Asc(char$) - char_a
check.l | 1 << pos
Next
If check & $3FFFFFF = $3FFFFFF
ProcedureReturn 1
EndIf
ProcedureReturn 0
EndProcedure
 
Procedure IsPangram_simple(String$)
String$ = LCase(string$)
found = 1
For a = Asc("a") To Asc("z")
; searches for every letter in whole string
If FindString(String$, Chr(a), 0) = 0
found = 0
EndIf
Next
ProcedureReturn found
EndProcedure
 
Debug IsPangram_fast("The quick brown fox jumps over lazy dogs.")
Debug IsPangram_simple("The quick brown fox jumps over lazy dogs.")
Debug IsPangram_fast("No pangram")
Debug IsPangram_simple("No pangram")

[edit] Python

Using set arithmetic:

import string, sys
if sys.version_info[0] < 3:
input = raw_input
 
def ispangram(sentence, alphabet=string.ascii_lowercase):
alphaset = set(alphabet)
return not alphaset - set(sentence.lower())
 
print ( ispangram(input('Sentence: ')) )

Sample output:

Sentence: The quick brown fox jumps over the lazy dog
True

[edit] R

Using the built-in R vector "letters":

checkPangram <- function(sentence){
my.letters <- tolower(unlist(strsplit(sentence, "")))
is.pangram <- all(letters %in% my.letters)
 
if (is.pangram){
cat("\"", sentence, "\" is a pangram! \n", sep="")
} else {
cat("\"", sentence, "\" is not a pangram! \n", sep="")
}
}
 

Sample output:

s1 <- "The quick brown fox jumps over the lazy dog"
s2 <- "The quick brown fox jumps over the sluggish dog"
checkPangram(s1)
"The quick brown fox jumps over the lazy dog" is a pangram!
checkPangram(s2)
"The quick brown fox jumps over the sluggish dog" is not a pangram!
 

[edit] Ruby

def pangram?(sentence)
unused_letters = ('a'..'z').to_a - sentence.downcase.chars.to_a
unused_letters.empty?
end
 
p pangram?('this is a sentence') # ==> false
p pangram?('The quick brown fox jumps over the lazy dog.') # ==> true

[edit] Scala

def is_pangram(sentence: String) = sentence.toLowerCase.filter(c => c >= 'a' && c <= 'z').toSet.size == 26
 
 
scala> is_pangram("This is a sentence")
res0: Boolean = false
 
scala> is_pangram("The quick brown fox jumps over the lazy dog")
res1: Boolean = true
 

[edit] Smalltalk

!String methodsFor: 'testing'!
isPangram
^((self collect: [:c | c asUppercase]) select: [:c | c >= $A and: [c <= $Z]]) asSet size = 26
 
 
'The quick brown fox jumps over the lazy dog.' isPangram
 

[edit] SNOBOL4

Works with: Macro Spitbol Works with: Snobol4+ Works with: CSnobol

        define('pangram(str)alfa,c') :(pangram_end)
pangram str = replace(str,&ucase,&lcase)
alfa = &lcase
pgr_1 alfa len(1) . c = :f(return)
str c :s(pgr_1)f(freturn)
pangram_end
 
define('panchk(str)tf') :(panchk_end)
panchk output = str
tf = 'False'; tf = pangram(str) 'True'
output = 'Pangram: ' tf :(return)
panchk_end
 
* # Test and display
panchk("The quick brown fox jumped over the lazy dogs.")
panchk("My girl wove six dozen plaid jackets before she quit.")
panchk("This 41-character string: it's a pangram!")
end

Output:

The quick brown fox jumped over the lazy dogs.
Pangram: True
My girl wove six dozen plaid jackets before she quit.
Pangram: True
This 41-character string: it's a pangram!
Pangram: False

[edit] Tcl

proc pangram? {sentence} {
set letters [regexp -all -inline {[a-z]} [string tolower $sentence]]
expr {
[llength [lsort -unique $letters]] == 26
}
}
 
puts [pangram? "This is a sentence"]; # ==> false
puts [pangram? "The quick brown fox jumps over the lazy dog."]; # ==> true

[edit] Ursala

 
#import std
 
is_pangram = ^jZ^(!@l,*+ @rlp -:~&) ~=`A-~ letters
 

example usage:

 
#cast %bL
 
test =
 
is_pangram* <
'The quick brown fox jumps over the lazy dog',
'this is not a pangram'>
 

output:

<true,false>

[edit] VBScript

[edit] Implementation

function pangram( s )
dim i
dim sKey
dim sChar
dim nOffset
sKey = "abcdefghijklmnopqrstuvwxyz"
for i = 1 to len( s )
sChar = lcase(mid(s,i,1))
if sChar <> " " then
if instr(sKey, sChar) then
nOffset = asc( sChar ) - asc("a") + 1
if nOffset > 1 then
sKey = left(sKey, nOffset - 1) & " " & mid( sKey, nOffset + 1)
else
sKey = " " & mid( sKey, nOffset + 1)
end if
end if
end if
next
pangram = ( ltrim(sKey) = vbnullstring )
end function
 
function eef( bCond, exp1, exp2 )
if bCond then
eef = exp1
else
eef = exp2
end if
end function

[edit] Invocation

wscript.echo eef(pangram("a quick brown fox jumps over the lazy dog"), "is a pangram", "is not a pangram")
wscript.echo eef(pangram(""), "is a pangram", "is not a pangram")"
Personal tools
Support