1
\$\begingroup\$

Problem

Write a program that can calculate the Hamming difference between two DNA strands.

GAGCCTACTAACGGGAT
CATCGTAATGACGGCCT
^ ^ ^  ^ ^    ^^

Code

object Hamming {
  def compute(s1: String, s2: String): Int = {
    if (s1.length != s2.length)
      throw new IllegalArgumentException()
    (s1.toList).zip(s2.toList)
               .filter(current => current._1 != current._2)
               .length
  }  
}

Test Suite

import org.scalatest._

class HammingSpecs extends FlatSpec with Matchers {
  it should "detect no difference between empty strands" in {
    Hamming.compute("", "") should be (0)
  }

  it should "detect no difference between identical strands" in {
    Hamming.compute("GGACTGA", "GGACTGA") should be (0)
  }

  it should "detect complete hamming distance in small strand" in {
    Hamming.compute("ACT", "GGA") should be (3)
  }

  it should "give hamming distance in off by one strand" in {
    Hamming.compute("GGACGGATTCTG", "AGGACGGATTCT") should be (9)
  }

  it should "give small hamming distance in middle somewhere" in {
    Hamming.compute("GGACG", "GGTCG") should be (1)
  }

  it should "give a larger distance" in {
    Hamming.compute("ACCAGGG", "ACTATGG") should be (2)
  }

  it should "be undefined for strands of unequal length" in {
    an[IllegalArgumentException] should be thrownBy {
      Hamming.compute("AAACTAGGGG", "AGGCTAGCGGTAGGAC")
    }
  }
}

Source

\$\endgroup\$
1
\$\begingroup\$

Strings have a .zip() method; calling .toList() is superfluous.

Instead of .filter(…) and .length(), use .count(…).

I'm not a fan of the name current, which has a connotation of iteration.

Avoid omitting braces with if statements. If you want to do so, put the body on the same line to avoid accidents.

object Hamming {
  def compute(s1: String, s2: String): Int = {
    if (s1.length != s2.length) throw new IllegalArgumentException()
    s1.zip(s2).count(pair => pair._1 != pair._2)
  }  
}
\$\endgroup\$
  • \$\begingroup\$ Is there a class diagram or something like that to take the reference of the methods on types? \$\endgroup\$ – CodeYogi Jun 23 '16 at 2:18
  • \$\begingroup\$ I just go by the official API documentation that I cited. I don't know if there is a better reference. \$\endgroup\$ – 200_success Jun 23 '16 at 3:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.