Advertisement
jdalbey

Hamming Distance

May 14th, 2015
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1.  
  2. /**
  3.  * The Hamming distance between two strings of equal length is the number of positions
  4.  * at which the corresponding symbols are different. In other words, it measures the
  5.  * minimum number of substitutions required to change one string into the other.
  6.  *
  7.  * @author jdalbey
  8.  * @version 0.1
  9.  */
  10. public class Hamming
  11. {
  12.     /**
  13.      * Return the hamming distance between two strings.
  14.      *
  15.      * @param  alpha a string
  16.      * @param  bravo a string
  17.      * @pre alpha.length() == bravo.length();
  18.      * @return number of positions at which corresponding characters differ
  19.      */
  20.     public static int getDistance(String alpha, String bravo)
  21.     {
  22.         int count = 0;
  23.         // Iterate through all characters in both strings
  24.         for (int pos = 0; pos < alpha.length(); pos++)
  25.         {
  26.             // If they don't match, increment the counter
  27.             if (alpha.charAt(pos) != bravo.charAt(pos))
  28.             {
  29.                 count++;
  30.             }
  31.         }
  32.         return count;
  33.     }
  34. }
  35.  
  36.  
  37. /**
  38.  * The test class HammingDistanceTest.
  39.  *
  40.  * @author jdalbey
  41.  * @version 0.1
  42.  */
  43. public class HammingDistanceTest extends junit.framework.TestCase
  44. {
  45.  
  46.     public void testOne()
  47.     {
  48.         assertEquals(0, Hamming.getDistance("abc", "abc"));
  49.         assertEquals(3, Hamming.getDistance("aaa", "bbb"));
  50.         assertEquals(1, Hamming.getDistance("baa", "aaa"));
  51.         assertEquals(1, Hamming.getDistance("aba", "aaa"));
  52.         assertEquals(1, Hamming.getDistance("aab", "aaa"));
  53.         assertEquals(2, Hamming.getDistance("bab", "aaa"));
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement