]> git.donarmstrong.com Git - biopieces.git/commitdiff
added hamming_dist method to bits.rb
authormartinahansen <martinahansen@74ccb610-7750-0410-82ae-013aeee3265d>
Mon, 7 Mar 2011 12:00:19 +0000 (12:00 +0000)
committermartinahansen <martinahansen@74ccb610-7750-0410-82ae-013aeee3265d>
Mon, 7 Mar 2011 12:00:19 +0000 (12:00 +0000)
git-svn-id: http://biopieces.googlecode.com/svn/trunk@1281 74ccb610-7750-0410-82ae-013aeee3265d

code_ruby/Maasha/lib/bits.rb
code_ruby/Maasha/lib/seq.rb
code_ruby/Maasha/test/test_bits.rb

index f6e52c8af644f88ce42901c7b190748e0fb30d0e..b976c8854d378d1c6f38010197666bcec824667d 100644 (file)
 
 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
 
+# Error class for all exceptions to do with String.
+class StringError < StandardError; end
+
 # Monkey patching Class String to add bitwise operators.
 # Behaviour matching Perl's:
 # http://perldoc.perl.org/perlop.html#Bitwise-String-Operators
 class String
+  # Method to that returns the case senstive Hamming Distance between two strings.
+  # http://en.wikipedia.org/wiki/Hamming_distance
+  def self.hamming_dist(str1, str2)
+    raise StringError, "Uneven string lengths: #{str1.length} != #{str2.length}" if str1.length != str2.length
+    (str1 ^ str2 ).count("\x01-\xff")
+  end
+
   # Method that performs bitwise AND operation where bits
   # are copied if they exists in BOTH operands. If the operand
   # sizes are different, the & operator methods acts as though
index 3bb65551d7be576d6ee3314345ff289ddba025b8..c4083237ff38018e3ace039eaac3fed5c32a5c76 100644 (file)
@@ -22,6 +22,8 @@
 
 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
 
+require 'bits'
+
 # Residue alphabets
 DNA     = %w[a t c g]
 RNA     = %w[a u c g]
index f9d582414223b763c632b55136a5cf3d047bdd82..c3e5951a0ffe6810a90e49f7b4d3f298a25014bd 100755 (executable)
@@ -5,6 +5,23 @@ require 'test/unit'
 require 'pp'
 
 class TestBits < Test::Unit::TestCase 
+  def test_Bits_hamming_dist_with_uneven_lengths_raises
+    assert_raises(StringError) { String.hamming_dist("ATCG", "ATC") }
+  end
+
+  def test_Bits_hamming_dist_with_even_lengths_dont_raise
+    assert_nothing_raised { String.hamming_dist("ATCG", "ATCG") }
+  end
+
+  def test_Bits_hamming_dist_returns_correctly
+    assert_equal(0, String.hamming_dist("ATCG", "ATCG"))
+    assert_equal(1, String.hamming_dist("ATCX", "ATCG"))
+    assert_equal(2, String.hamming_dist("ATXX", "ATCG"))
+    assert_equal(2, String.hamming_dist("ATcg", "ATCG"))
+    assert_equal(3, String.hamming_dist("AXXX", "ATCG"))
+    assert_equal(4, String.hamming_dist("XXXX", "ATCG"))
+  end
+
   def test_Bits_AND_with_equal_length_returns_correctly
     assert_equal("ABCD", "abcd" & "____")
   end