Pangram checker
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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.
ActionScript 2.0
<lang ActionScript> //i know this method is very barbaric, but it does the job with just basic commands. function pangram(k:String) { var hasA:Boolean = false; var hasB:Boolean = false; var hasC:Boolean = false; var hasD:Boolean = false; var hasE:Boolean = false; var hasF:Boolean = false; var hasG:Boolean = false; var hasH:Boolean = false; var hasI:Boolean = false; var hasJ:Boolean = false; var hasK:Boolean = false; var hasL:Boolean = false; var hasM:Boolean = false; var hasN:Boolean = false; var hasO:Boolean = false; var hasP:Boolean = false; var hasQ:Boolean = false; var hasR:Boolean = false; var hasS:Boolean = false; var hasT:Boolean = false; var hasU:Boolean = false; var hasV:Boolean = false; var hasW:Boolean = false; var hasX:Boolean = false; var hasY:Boolean = false; var hasZ:Boolean = false; for (i=0; i<=k.length-1; i++) { if (k.charAt(i) == "A" or k.charAt(i) == "a") { hasA = true; } if (k.charAt(i) == "B" or k.charAt(i) == "b") { hasB = true; } if (k.charAt(i) == "C" or k.charAt(i) == "c") { hasC = true; } if (k.charAt(i) == "D" or k.charAt(i) == "d") { hasD = true; } if (k.charAt(i) == "E" or k.charAt(i) == "e") { hasE = true; } if (k.charAt(i) == "F" or k.charAt(i) == "f") { hasF = true; } if (k.charAt(i) == "G" or k.charAt(i) == "g") { hasG = true; } if (k.charAt(i) == "H" or k.charAt(i) == "h") { hasH = true; } if (k.charAt(i) == "I" or k.charAt(i) == "i") { hasI = true; } if (k.charAt(i) == "J" or k.charAt(i) == "j") { hasJ = true; } if (k.charAt(i) == "K" or k.charAt(i) == "k") { hasK = true; } if (k.charAt(i) == "L" or k.charAt(i) == "l") { hasL = true; } if (k.charAt(i) == "M" or k.charAt(i) == "m") { hasM = true; } if (k.charAt(i) == "N" or k.charAt(i) == "n") { hasN = true; } if (k.charAt(i) == "O" or k.charAt(i) == "o") { hasO = true; } if (k.charAt(i) == "P" or k.charAt(i) == "p") { hasP = true; } if (k.charAt(i) == "Q" or k.charAt(i) == "q") { hasQ = true; } if (k.charAt(i) == "R" or k.charAt(i) == "r") { hasR = true; } if (k.charAt(i) == "S" or k.charAt(i) == "s") { hasS = true; } if (k.charAt(i) == "T" or k.charAt(i) == "t") { hasT = true; } if (k.charAt(i) == "U" or k.charAt(i) == "u") { hasU = true; } if (k.charAt(i) == "V" or k.charAt(i) == "v") { hasV = true; } if (k.charAt(i) == "W" or k.charAt(i) == "w") { hasW = true; } if (k.charAt(i) == "X" or k.charAt(i) == "x") { hasX = true; } if (k.charAt(i) == "Y" or k.charAt(i) == "y") { hasY = true; } if (k.charAt(i) == "Z" or k.charAt(i) == "z") { hasZ = true; } } if (hasA == true and hasB == true and hasC == true and hasD == true and hasE == true and hasF == true and hasG == true and hasH == true and hasI == true and hasJ == true and hasK == true and hasL == true and hasM == true and hasN == true and hasO == true and hasP == true and hasQ == true and hasR == true and hasS == true and hasT == true and hasU == true and hasV == true and hasW == true and hasX == true and hasY == true and hasZ == true) { return true; } else { return false; } }
trace(pangram("the QuiCk Brown Fox jumps over the lazy dog")); //true </lang>
Ada
Using Sets <lang Ada> 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; </lang> Output:
FALSE TRUE TRUE FALSE
ALGOL 68
<lang algol68># 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
)</lang> Output:
"Big fjiords vex quick waltz nymph" is a pangram! "The quick brown fox jumps over a lazy dog" is a pangram!
AutoHotkey
<lang 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</lang>
BASIC
<lang 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</lang>
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?
BBC BASIC
<lang bbcbasic> FOR test% = 1 TO 2
READ test$ PRINT """" test$ """ " ; IF FNpangram(test$) THEN PRINT "is a pangram" ELSE PRINT "is not a pangram" ENDIF NEXT test% END DATA "The quick brown fox jumped over the lazy dog" DATA "The five boxing wizards jump quickly" DEF FNpangram(A$) LOCAL C% A$ = FNlower(A$) FOR C% = ASC("a") TO ASC("z") IF INSTR(A$, CHR$(C%)) = 0 THEN = FALSE NEXT = TRUE DEF FNlower(A$) LOCAL A%, C% FOR A% = 1 TO LEN(A$) C% = ASCMID$(A$,A%) IF C% >= 65 IF C% <= 90 MID$(A$,A%,1) = CHR$(C%+32) NEXT = A$</lang>
Output:
"The quick brown fox jumped over the lazy dog" is not a pangram "The five boxing wizards jump quickly" is a pangram
Brat
<lang brat>pangram? = { sentence |
letters = [: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]
sentence.downcase!
letters.reject! { l | sentence.include? l }
letters.empty?
}
p pangram? 'The quick brown fox jumps over the lazy dog.' #Prints true p pangram? 'Probably not a pangram.' #Prints false</lang>
Alternative version:
<lang brat>pangram? = { sentence |
sentence.downcase.dice.unique.select(:alpha?).length == 26
}</lang>
C
<lang C>#include <stdio.h>
- include <stdlib.h>
- include <string.h>
int isPangram(char *string) { char ch, wasused[26], *sp; int total = 0;
memset(wasused, 0, sizeof(wasused)); for (sp=string; ch = *sp; sp++) { int index;
if('A'<=ch&&ch<='Z') index = ch-'A'; else if('a'<=ch&&ch<='z') index = ch-'a'; else continue; if(!wasused[index]) { wasused[index] = 1; total++; } } return (total==26); }
main(int argc, char *argv[]) { char *pangram = "The quick brown fox jumps over the lazy dog."; char *not_a_pangram = "The qu1ck brown fox jumps over the lazy d0g."; printf("\"%s\" is %sa pangram\n", pangram, isPangram(pangram)?"":"not "); printf("\"%s\" is %sa pangram\n", not_a_pangram, isPangram(not_a_pangram)?"":"not "); return 0; }</lang>
Using bitmask
<lang c>#include <stdio.h>
int pangram(char *s) { int c, mask = (1 << 26) - 1; while ((c = (*s++)) != '\0') /* 0x20 converts lowercase to upper */ if ((c &= ~0x20) <= 'Z' && c >= 'A') mask &= ~(1 << (c - 'A'));
return !mask; }
int main() { int i; char *s[] = { "The quick brown fox jumps over lazy dogs.", "The five boxing wizards dump quickly.", };
for (i = 0; i < 2; i++) printf("%s: %s\n", pangram(s[i]) ? "yes" : "no ", s[i]);
return 0; }</lang>output<lang>yes: The quick brown fox jumps over lazy dogs. no : The five boxing wizards dump quickly.</lang>
C#
C# 3.0 or higher (.NET Framework 3.5 or higher)
<lang csharp>using System; using System.Linq;
static class Program {
static bool IsPangram(this string text, string alphabet = "abcdefghijklmnopqrstuvwxyz") { return alphabet.All(text.ToLower().Contains); }
static void Main(string[] arguments) { Console.WriteLine(arguments.Any() && arguments.First().IsPangram()); }
}</lang>
Any version of C# language and .NET Framework
<lang csharp>using System;
namespace PangrammChecker {
public class PangrammChecker { public static bool IsPangram(string str) { bool[] isUsed = new bool[26]; int ai = (int)'a'; int total = 0; for (CharEnumerator en = str.ToLower().GetEnumerator(); en.MoveNext(); ) { int d = (int)en.Current - ai; if (d >= 0 && d < 26) if (!isUsed[d]) { isUsed[d] = true; total++; } } return (total == 26); } }
class Program { static void Main(string[] args) { string str1 = "The quick brown fox jumps over the lazy dog."; string str2 = "The qu1ck brown fox jumps over the lazy d0g."; Console.WriteLine("{0} is {1}a pangram", str1, PangrammChecker.IsPangram(str1)?"":"not "); Console.WriteLine("{0} is {1}a pangram", str2, PangrammChecker.IsPangram(str2)?"":"not "); Console.WriteLine("Press Return to exit"); Console.ReadLine(); } }
}</lang>
C++
<lang cpp>#include <algorithm>
- include <cctype>
- include <string>
using namespace std;
const string alphabet("abcdefghijklmnopqrstuvwxyz"); // sorted, no duplicates
bool is_pangram(string s) {
// Convert to lower case. transform(s.begin(), s.end(), s.begin(), ::tolower); // Convert to a sorted sequence of unique characters. sort(s.begin(), s.end()); // Is the second sequence a subset of the first sequence? return includes(s.begin(), s.end(), alphabet.begin(), alphabet.end());
}</lang>
Common Lisp
<lang 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))))</lang>
D
A low-level solution: <lang d>pure nothrow bool isPangram(string text) {
uint bitset; foreach (c; text) { if (c >= 'a' && c <= 'z') bitset |= (1u << (c - 'a')); else if (c >= 'A' && c <= 'Z') bitset |= (1u << (c - 'A')); } return bitset == 0b11_11111111_11111111_11111111;
}
void main() {
assert(isPangram("the quick brown fox jumps over the lazy dog")); assert(!isPangram("ABCDEFGHIJKLMNOPQSTUVWXYZ")); assert(!isPangram("ABCDEFGHIJKL.NOPQRSTUVWXYZ")); assert(isPangram("ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ"));
}</lang>
Internationalized version:
<lang d>import std.string, std.traits, std.uni;
enum Alphabet : dstring {
DE = "abcdefghijklmnopqrstuvwxyzßäöü", EN = "abcdefghijklmnopqrstuvwxyz", SV = "abcdefghijklmnopqrstuvwxyzåäö"
}
bool isPangram(T)(T[] s, dstring alpha = Alphabet.EN) if (isSomeChar!T) {
foreach (c; alpha) if (indexOf(s, c) == -1 && indexOf(s, toUniUpper(c)) == -1) return false; return true;
}</lang>
<lang d>unittest {
assert(isPangram("the quick brown fox jumps over the lazy dog".dup, Alphabet.EN)); assert(isPangram("Falsches Üben von Xylophonmusik quält jeden größeren Zwerg", Alphabet.DE)); assert(isPangram("Yxskaftbud, ge vår wczonmö iqhjälp"w, Alphabet.SV));
}</lang>
Clojure
<lang lisp>(defn pangram? [s]
(let [letters (into #{} "abcdefghijklmnopqrstuvwxyz")] (= (->> s .toLowerCase (filter letters) (into #{})) letters)))</lang>
Delphi
<lang Delphi>program PangramChecker;
{$APPTYPE CONSOLE}
uses StrUtils;
function IsPangram(const aString: string): Boolean; var
c: char;
begin
for c := 'a' to 'z' do if not ContainsText(aString, c) then Exit(False);
Result := True;
end;
begin
Writeln(IsPangram('The quick brown fox jumps over the lazy dog')); // true Writeln(IsPangram('Not a panagram')); // false
end.</lang>
E
<lang e>def isPangram(sentence :String) {
return ("abcdefghijklmnopqrstuvwxyz".asSet() &! sentence.toLowerCase().asSet()).size() == 0
}</lang>
&!
is the “but-not” or set difference operator.
Erlang
<lang Erlang>-module(pangram). -export([is_pangram/1]). -import(lists, [any/2, all/2, seq/2]). -import(string, [to_upper/1]).
is_pangram(S) ->
Alphabet = seq(hd("A"), hd("Z")), all(fun(X) -> any(fun(Y) -> X == Y end, to_upper(S)) end, Alphabet).</lang>
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: <lang fsharp>let isPangram (str: string) = (set['a'..'z'] - set(str.ToLower())).IsEmpty</lang>
Factor
<lang factor>: pangram? ( str -- ? )
[ "abcdefghijklmnopqrstuvwxyz" ] dip >lower diff length 0 = ;
"How razorback-jumping frogs can level six piqued gymnasts!" pangram? .</lang>
Forth
<lang 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</lang>
Fortran
<lang fortran>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</lang> Example: <lang fortran>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</lang> Output: <lang>This is a sentence. F The five boxing wizards jumped quickly. T</lang>
Go
<lang go>package main
import "fmt"
func main() {
for _, s := range []string{ "The quick brown fox jumps over the lazy dog.", `Watch "Jeopardy!", Alex Trebek's fun TV quiz game.`, "Not a pangram.", } { if pangram(s) { fmt.Println("Yes:", s) } else { fmt.Println("No: ", s) } }
}
func pangram(s string) bool {
var rep [26]bool var count int for _, c := range s { if c >= 'a' { if c > 'z' { continue } c -= 'a' } else { if c < 'A' || c > 'Z' { continue } c -= 'A' } if !rep[c] { if count == 25 { return true } rep[c] = true count++ } } return false
}</lang> Output:
Yes: The quick brown fox jumps over the lazy dog. Yes: Watch "Jeopardy!", Alex Trebek's fun TV quiz game. No: Not a pangram.
Haskell
<lang 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!"</lang>
HicEst
<lang HicEst>PangramBrokenAt("This is a Pangram.") ! => 2 (b is missing) PangramBrokenAt("The quick Brown Fox jumps over the Lazy Dog") ! => 0 (OK)
FUNCTION PangramBrokenAt(string)
CHARACTER string, Alfabet="abcdefghijklmnopqrstuvwxyz" PangramBrokenAt = INDEX(Alfabet, string, 64) ! option 64: verify = 1st letter of string not in Alfabet
END</lang>
Icon and Unicon
A panagram procedure: <lang Icon>procedure panagram(s) #: return s if s is a panagram and fail otherwise if (map(s) ** &lcase) === &lcase then return s end</lang>
And a main to drive it: <lang Icon>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</lang>
Ioke
<lang ioke>Text isPangram? = method(
letters = "abcdefghijklmnopqrstuvwxyz" chars text = self lower chars letters map(x, text include?(x)) reduce(&&)
)</lang>
Here is an example of it's use in the Ioke REPL:
<lang ioke> 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</lang>
J
Solution: <lang j>require 'strings' isPangram=: (a. {~ 97+i.26) */@e. tolower</lang>
Example use: <lang j> isPangram 'The quick brown fox jumps over the lazy dog.' 1
isPangram 'The quick brown fox falls over the lazy dog.'
0</lang>
Java
<lang java5>public class Pangram {
public static boolean isPangram(String test){ for (char a = 'A'; a <= 'Z'; a++) if (!test.contains(a) && !test.contains(Character.toLowerCase(a))) return false; return true; }
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 }
}</lang> Output:
true false true false false true false
JavaScript
<lang javascript>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</lang>
K
<lang k>lcase : _ci 97+!26 ucase : _ci 65+!26 tolower : {@[x;p;:;lcase@n@p:&26>n:ucase?/:x]} panagram: {&/lcase _lin tolower x}</lang>
Example: <lang k> panagram "The quick brown fox jumps over the lazy dog" 1
panagram "Panagram test"
0</lang>
Liberty BASIC
<lang lb>'Returns 0 if the string is NOT a pangram or >0 if it IS a pangram string$ = "The quick brown fox jumps over the lazy dog."
Print isPangram(string$)
Function isPangram(string$)
string$ = Lower$(string$) For i = Asc("a") To Asc("z") isPangram = Instr(string$, chr$(i)) If isPangram = 0 Then Exit Function Next i
End Function</lang>
Logo
<lang 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</lang>
Lua
<lang 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")</lang>
MATLAB
<lang 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</lang>
Sample Output: <lang MATLAB>isPangram('The quick brown fox jumps over the lazy dog.')
ans =
1</lang>
Objeck
<lang objeck> bundle Default {
class Pangram { function : native : IsPangram(test : String) ~ Bool { for(a := 'A'; a <= 'Z'; a += 1;) { if(test->Find(a) < 0 & test->Find(a->ToLower()) < 0) { return false; }; };
return true; }
function : Main(args : String[]) ~ Nil { IsPangram("the quick brown fox jumps over the lazy dog")->PrintLine(); # true IsPangram("the quick brown fox jumped over the lazy dog")->PrintLine(); # false, no s IsPangram("ABCDEFGHIJKLMNOPQRSTUVWXYZ")->PrintLine(); # true IsPangram("ABCDEFGHIJKLMNOPQSTUVWXYZ")->PrintLine(); # false, no r IsPangram("ABCDEFGHIJKL.NOPQRSTUVWXYZ")->PrintLine(); # false, no m IsPangram("ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ")->PrintLine(); # true IsPangram("")->PrintLine(); # false } }
} </lang>
NetRexx
NetRexx's verify
built–in method is all you need!
<lang NetRexx>/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
A2Z = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
pangrams = create_samples
loop p_ = 1 to pangrams[0]
pangram = pangrams[p_] q_ = A2Z.verify(pangram.upper) -- <= it basically all happens in this function call! say pangram.left(64)'\-' if q_ == 0 then - say ' [OK, a pangram]' else - say ' [Not a pangram. Missing:' A2Z.substr(q_, 1)']' end p_
method create_samples public static returns Rexx
pangrams =
x_ = 0 x_ = x_ + 1; pangrams[0] = x_; pangrams[x_] = 'The quick brown fox jumps over a lazy dog.' -- best/shortest pangram x_ = x_ + 1; pangrams[0] = x_; pangrams[x_] = 'The quick brown fox jumps over the lazy dog.' -- not as short but at least it's still a pangram x_ = x_ + 1; pangrams[0] = x_; pangrams[x_] = 'The quick brown fox jumped over the lazy dog.' -- common misquote; not a pangram x_ = x_ + 1; pangrams[0] = x_; pangrams[x_] = 'The quick onyx goblin jumps over the lazy dwarf.' x_ = x_ + 1; pangrams[0] = x_; pangrams[x_] = 'Bored? Craving a pub quiz fix? Why, just come to the Royal Oak!' -- (Used to advertise a pub quiz in Bowness-on-Windermere)
return pangrams
</lang> Output:
The quick brown fox jumps over a lazy dog. [OK, a pangram] The quick brown fox jumps over the lazy dog. [OK, a pangram] The quick brown fox jumped over the lazy dog. [Not a pangram. Missing: S] The quick onyx goblin jumps over the lazy dwarf. [OK, a pangram] Bored? Craving a pub quiz fix? Why, just come to the Royal Oak! [OK, a pangram]
OCaml
<lang 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</lang>
<lang ocaml>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.";
- </lang>
outputs:
false -- this is a sentence true -- The quick brown fox jumps over the lazy dog.
Oz
<lang 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."}}</lang>
PARI/GP
<lang parigp>pangram(s)={
s=vecsort(Vec(s),,8); for(i=97,122, if(!setsearch(s,Strchr(i)) && !setsearch(s,Strchr(i-32)), return(0) ) ); 1
};
pangram("The quick brown fox jumps over the lazy dog.") pangram("The quick brown fox jumps over the lazy doe.")</lang>
Perl
<lang 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.';</lang>
Perl 6
<lang perl>sub pangram($s) {
Set.new("a".."z").subsetorequal($s.comb);
}</lang>
PicoLisp
<lang PicoLisp>(de isPangram (Str)
(not (diff '`(chop "abcdefghijklmnopqrstuvwxyz") (chop (lowc Str)) ) ) )</lang>
PHP
<lang php>function isPangram($text) {
foreach (str_split($text) as $c) { if ($c >= 'a' && $c <= 'z') $bitset |= (1 << (ord($c) - ord('a'))); else if ($c >= 'A' && $c <= 'Z') $bitset |= (1 << (ord($c) - ord('A'))); } return $bitset == 67108863;
}
$test = array(
"the quick brown fox jumps over the lazy dog", "the quick brown fox jumped over the lazy dog", "ABCDEFGHIJKLMNOPQSTUVWXYZ", "ABCDEFGHIJKL.NOPQRSTUVWXYZ", "ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ"
);
foreach ($test as $str)
echo "$str : ", isPangram($str) ? 'T' : 'F', '
';</lang>
the quick brown fox jumps over the lazy dog : T the quick brown fox jumped over the lazy dog : F ABCDEFGHIJKLMNOPQSTUVWXYZ : F ABCDEFGHIJKL.NOPQRSTUVWXYZ : F ABC.D.E.FGHI*J/KL-M+NO*PQ R STUVWXYZ : T
PL/I
<lang 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; </lang>
Output:
<lang> Please type a sentence
the quick brown fox jumps over the lazy dog The sentence is a pangram. </lang>
Prolog
Works with SWI-Prolog
<lang 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]). </lang> output <lang>?- pangram_example. the quick brown fox jumps over the lazy dog --> ok the quick brown fox jumped over the lazy dog --> ko true.</lang>
PureBasic
<lang 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")</lang>
Python
Using set arithmetic: <lang python>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: ')) )</lang>
Sample output:
Sentence: The quick brown fox jumps over the lazy dog True
R
Using the built-in R vector "letters": <lang R>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="") }
}
</lang>
Sample output: <lang>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! </lang>
Retro
<lang Retro>: isPangram? ( $-f )
^strings'toLower heap [ 27 allot ] preserve [ @ 'a - dup 0 25 within [ [ 'a + ] [ here + ] bi ! ] &drop if ] ^types'STRING each@ here "abcdefghijklmnopqrstuvwxyz" compare ;</lang>
REXX
<lang REXX> /*REXX program to check if a string (sentence) is a pangram. */
abc='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
do forever /*keep promting until a null or blank. */ say say '----- Please enter a pangramic sentence:' say pull y if y= then leave ?=verify(abc,y) /*see if all letters are present. */
if ?==0 then say 'Sentence is a pangram.' else say "Sentence isn't a pangram, missing:" substr(abc,?,1) say end
say '----- PANGRAM program ended. -----' </lang> Output:
----- Please enter a pangramic sentence: The quick brown fox jumped over the lazy dog. Sentence isn't a pangram, missing: S ----- Please enter a pangramic sentence: The quick brown fox JUMPS over the lazy dog!!! Sentence is a pangram. ----- Please enter a pangramic sentence: ----- PANGRAM program ended. -----
Ruby
<lang 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</lang>
Scala
<lang scala>def is_pangram(sentence: String) = sentence.toLowerCase.filter(c => c >= 'a' && c <= 'z').toSet.size == 26 </lang>
<lang scala> 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 </lang>
Smalltalk
<lang smalltalk>!String methodsFor: 'testing'! isPangram ^((self collect: [:c | c asUppercase]) select: [:c | c >= $A and: [c <= $Z]]) asSet size = 26 </lang>
<lang smalltalk> 'The quick brown fox jumps over the lazy dog.' isPangram </lang>
SNOBOL4
<lang SNOBOL4> 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</lang>
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
Tcl
<lang 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</lang>
TUSCRIPT
<lang tuscript> $$ MODE TUSCRIPT SET alfabet="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" SET sentences = * DATA The quick brown fox jumps over the lazy dog DATA the quick brown fox falls over the lazy dog LOOP s=sentences SET chars=STRINGS (s,":</:") SEt chars=ALPHA_SORT (chars) SET chars=REDUCE (chars) IF (chars==alfabet) THEN PRINT "pangram: ",s ELSE PRINT "no pangram: ",s ENDIF ENDLOOP </lang> Output:
pangram: The quick brown fox jumps over the lazy dog no pangram: the quick brown fox falls over the lazy dog
Ursala
<lang Ursala>
- import std
is_pangram = ^jZ^(!@l,*+ @rlp -:~&) ~=`A-~ letters </lang> example usage: <lang Ursala>
- cast %bL
test =
is_pangram* <
'The quick brown fox jumps over the lazy dog', 'this is not a pangram'>
</lang> output:
<true,false>
VBScript
Implementation
<lang vb>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</lang>
Invocation
<lang vb>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")"</lang>
- Programming Tasks
- Solutions by Programming Task
- ActionScript 2.0
- Ada
- ALGOL 68
- AutoHotkey
- BASIC
- BBC BASIC
- Brat
- C
- C sharp
- C++
- Common Lisp
- D
- Clojure
- Delphi
- E
- Erlang
- F Sharp
- Factor
- Forth
- Fortran
- Go
- Haskell
- HicEst
- Icon
- Unicon
- Ioke
- J
- Java
- JavaScript
- K
- Liberty BASIC
- Logo
- Lua
- MATLAB
- Objeck
- NetRexx
- OCaml
- Oz
- PARI/GP
- Perl
- Perl 6
- PicoLisp
- PHP
- PL/I
- Prolog
- PureBasic
- Python
- R
- Retro
- REXX
- Ruby
- Scala
- Smalltalk
- SNOBOL4
- Tcl
- TUSCRIPT
- Ursala
- VBScript