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


i'm attempting create function returns number of values in array. far have following code, it's not working:

(a: array[int]): int = {   var howmanyeven = 0   for(i <-0 a.length) {     if(a(i)%2==0){       howmanyeven+= 1     }     howmanyeven   } 

in addition, reason i'm stumped how return number of odd values in array. methods off? guess i'm stumped methods use generate desired output.

you have off-by-one error (ignoring other typos , missing information), in you're trying go 0 a.length. if length 10, you're going 0 10, 11 indices. should a.length - 1.

you avoid having reason off-by-one errors using functional approach. same thing can accomplished in 1 line using standard methods in 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 method in collections library counts elements in collection satisfy boolean property. in case, checking element even.

i suggest having read of methods available on list, example. scala collections library rich, , has methods want do. it's matter of finding right 1 (or combination of). can see, java way of setting loops , using mutable variables tends error prone, , in scala best avoid that.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -