meow smix
meow smix

Reputation: 21

How to create a scala function that returns the number of even values in an array?

I'm attempting to create a function that returns the number of even values in an array. So far I have the following code, but it's not working:

(a: Array[Int]): Int = {
  var howManyEven = 0
  for(i <-0 to a.length) {
    if(a(i)%2==0){
      howManyEven+= 1
    }
    howManyEven
  }

In addition, for some reason I'm stumped as to how to return the number of odd values in an array. Are my methods off? I guess I'm just stumped about what methods to use to generate my desired output.

Upvotes: 2

Views: 575

Answers (2)

Puneeth Reddy V
Puneeth Reddy V

Reputation: 1568

You can also achieve this by using filter or groupBy

def howManyEven(a: Array[Int]): Int = a.filter(_%2==0).size

def howManyEven(a: Array[Int]): Int = a.groupBy(_ % 2 == 0).get(true).get.size

Upvotes: 0

Michael Zajac
Michael Zajac

Reputation: 55569

You have an off-by-one error (ignoring other typos and missing information), in that you're trying to go from 0 to a.length. But if the length is 10, then you're going from 0 to 10, which is 11 indices. It should be a.length - 1.

You could avoid having to reason about off-by-one errors by using a functional approach. The same thing can be accomplished in one line using standard methods in the collections library.

def howManyEven(a: Array[Int]): Int = a.count(_ % 2 == 0)

scala> howManyEven(Array(1, 2, 3, 4, 6, 8, 9, 10, 11))
res1: Int = 5

count is a method in the collections library that counts the elements in a collection that satisfy a Boolean property. In this case, checking that an element is even.

I suggest having a read of the methods available on List, for example. The Scala collections library is very rich, and has methods for almost anything you want to do. It's just a matter of finding the right one (or combination of). As you can see, the Java way of setting up for loops and using mutable variables tends to be error prone, and in Scala it is best to avoid that.

Upvotes: 7

Related Questions