HiveBrain v1.2.0
Get Started
← Back to all entries
gotchaMinor

Count chars difference between two strings

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
differencetwobetweencountcharsstrings

Problem

Given two strings with the same length, we check how many chars on the same positions are different. For example: ABCD and ABBD should return 1. Here is a link to a gist with tests, to have a better understanding of what I'm building.
Here is my solution:

object Hamming {

  def compute(str1: String, str2: String):Int = {
    if (str1.length != str2.length)
      throw new IllegalArgumentException("Strings have different length")
    (0 to str1.length - 1).filter(i => str1(i) != str2(i)).size
  }

}

Solution

How about this variant?

object Hamming {

    def apply(a: String, b: String): Int = if (a.length != b.length) {
        throw new IllegalArgumentException(s"Strings a=$a and b=$b have different length.")
    } else a.zip(b).count {
        case (charA, charB) => charA != charB
    }

}


The zip-function does create a new collection of tuples with two corresponding chars side by side in every tuple. (Char, Char)
The count-function counts the number of elements for which a boolean evaluation function, passed as an argument, returns true. This should work not only for characters, because it uses pattern matching. Also if there are two arguments of the same type (e.g. for comparison) and I cannot further specify what they are, then I like to name them a and b.
I cannot tell if this solution is faster than yours, but I don't think there will be a significant difference.

P.S.:

  • I see the function is named compute. Thats really general and abstract. I named it apply. It can be called like this: Hamming("Alice", "Bob")



  • Look at what I did with the brackets.



-
If you would like to use the function for other sequences than characters you can change the snippet to this:

def apply(a: Seq[_], b: Seq[_]): Int = if (a.size != b.size) {
    throw new IllegalArgumentException("Parameters have different length.")
} else a.zip(b).count {
    case (charA, charB) => charA != charB
}

Code Snippets

object Hamming {

    def apply(a: String, b: String): Int = if (a.length != b.length) {
        throw new IllegalArgumentException(s"Strings a=$a and b=$b have different length.")
    } else a.zip(b).count {
        case (charA, charB) => charA != charB
    }

}
def apply(a: Seq[_], b: Seq[_]): Int = if (a.size != b.size) {
    throw new IllegalArgumentException("Parameters have different length.")
} else a.zip(b).count {
    case (charA, charB) => charA != charB
}

Context

StackExchange Code Review Q#95420, answer score: 4

Revisions (0)

No revisions yet.