Search code examples
scalaoutliersparity

"Find the Parity Outlier Code Wars (Scala)"


I am doing some of CodeWars challenges recently and I've got a problem with this one.

"You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" N."

I've looked at some solutions, that are already on our website, but I want to solve the problem using my own approach.

The main problem in my code, seems to be that it ignores negative numbers even though I've implemented Math.abs() method in scala.

If you have an idea how to get around it, that is more than welcome.

Thanks a lot

object Parity {

  var even = 0
  var odd = 0
  var result = 0

  def findOutlier(integers: List[Int]): Int = {

    for (y <- 0 until integers.length) {
      if (Math.abs(integers(y)) % 2 == 0)
        even += 1
      else
        odd += 1
    }

    if (even == 1) {
      for (y <- 0 until integers.length) {
        if (Math.abs(integers(y)) % 2 == 0)
          result = integers(y)
      }
    } else {
      for (y <- 0 until integers.length) {
        if (Math.abs(integers(y)) % 2 != 0)
          result = integers(y)
      }
    }
    result
  }

Solution

  • Your code handles negative numbers just fine. The problem is that you rely on mutable sate, which leaks between runs of your code. Your code behaves as follows:

    val l = List(1,3,5,6,7)
    println(Parity.findOutlier(l)) //6
    println(Parity.findOutlier(l)) //7
    println(Parity.findOutlier(l)) //7
    

    The first run is correct. However, when you run it the second time, even, odd, and result all have the values from your previous run still in them. If you define them inside of your findOutlier method instead of in the Parity object, then your code gives correct results.

    Additionally, I highly recommend reading over the methods available to a Scala List. You should almost never need to loop through a List like that, and there are a number of much more concise solutions to the problem. Mutable var's are also a pretty big red flag in Scala code, as are excessive if statements.