0

Here the requirement is to compare both the array elements a(i) and b(i). And update the

If a[i]>b[i] , then a is awarded 1 point
If b[i]>a[i] , then b is awarded 1 point

object MyWizard extends App {
    def compareTriplets(a:Array[Int],b:Array[Int]):Array[Int]= {
        var aCount=0
        var bCount=0
        for(i<-0 to a.length-1){
            for(j<-0 to b.length-1){
                if(i==j) {
                    if(a(i)>b(i)){
                        aCount=aCount+1
                    }else if(a(i)<b(i)){
                        bCount=bCount+1
                    }
                }
            }
        }
        val c:Array[Int]=Array(aCount,bCount)
        c
    }
    println(compareTriplets(Array(1,32,3),Array(453,2,1)))
}
1
  • That is the way Arrays are printed. You can use array.mkString("[", ", ", "]") to get a nice string representation of your data. Or do not use Arrays*+ but rather a **List which is a more high level and idiomatic data structure in Scala. Also, I would recommend you to do not use mutability and loops, but higher-order functions or recursion. Also, if the result always has two elements do not return a collection. but a tuple. Also, it seems you are not that versed in Scala, I would recommend you to follow some tutorials. Commented Apr 1, 2020 at 15:22

2 Answers 2

2

Here is a more efficient, idiomatic, generic and simpler implementation of your algorithm.

// This works for any type as long as we know how to compare instances of it.
def compareTriplets[T : Ordering](as: List[T], bs: List[T]): (Int, Int) = {
  import Ordering.Implicits._ // Provides the comparison operators.

  (as lazyZip bs).foldLeft((0, 0)) {
    case ((aCount, bCount), (a, b)) =>
      if (a > b) (aCount + 1, bCount)
      else if (a < b) (aCount, bCount + 1)
      else (aCount, bCount)
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for helping. But lazyZip is throwing compilation error even after importing import Ordering Implicits.
@KrishnaKumar ah sorry, laxyZip was added on 2.13 if you are in an older version, just use zip.
-1

use a toString() method because it is being interpreted as its data address, not a string format of the data. Here is a simple geeksForGeeks example: https://www.geeksforgeeks.org/scala-map-tostring-method-with-example/

1 Comment

pritnln always calls toString the problem is that the toString of an Array prints its address instead of its values, because of Java geniuses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.