Saturday 25 July 2015

Check for pangram

A sentence is said to be pangram, if for a given alphabet, sentence contain every character of alphabet at least once.

Following are some of the pangrams in English alphabet, since they contain each alphabet of English at least once.

The quick brown fox jumps over the lazy dog.
Pack my box with five dozen liquor jugs.
Sphinx of black quartz, judge my vow.
Waltz, nymph, for quick jigs vex Bud.

Mr. Jock, TV quiz PhD, bags few lynx.
import java.util.BitSet;
import java.util.Objects;

public class Pangram {
 public static boolean isPangram(String str) {
  Objects.nonNull(str);

  if (str.length() < 26)
   return false;

  BitSet bits = new BitSet(26);

  String lowerCase = str.toLowerCase();

  for (int i = 0; i < str.length(); i++) {
   int val = lowerCase.charAt(i) - 'a';
   if (val > -1 && val < 26)
    bits.set(val);
  }

  return (bits.cardinality() == 26);
 }
}


Following is the junit test case for above application.
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class PangramTest {

 @Test
 public void test1() {
  assertTrue(Pangram
    .isPangram("The quick brown fox jumps over the lazy dog."));
  assertTrue(Pangram
    .isPangram("Pack my box with five dozen liquor jugs."));
  assertTrue(Pangram.isPangram("Sphinx of black quartz, judge my vow."));
  assertTrue(Pangram.isPangram("Waltz, nymph, for quick jigs vex Bud."));
  assertTrue(Pangram.isPangram("Mr. Jock, TV quiz PhD, bags few lynx."));

  assertFalse(Pangram
    .isPangram("Hello, How are you, i am fine what about you"));
 }

 @Test(expected = NullPointerException.class)
 public void test2() {
  assertFalse(Pangram.isPangram(null));
 }
}



No comments:

Post a Comment