Q:

Scala program to find the odd occurrences in an array

belongs to collection: Scala Array Programs

0

Here, we will create a program that will count the occurrences of odd elements in an array and return the elements with odd occurrences.

The are many elements in the arrays and we will count the total number of occurrences of odd elements in the array.

Example:

    Array: {1, 5, 1, 5, 5}

    Occurrence of 1 is 2 
    Occurrence of 5 is 3.

    Now, 5 has an odd occurrence.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

let see a program to find the odd occurrences in Array:

object MyClass {
    def solution(a: Array[Int]): Int = {
        def inner(l: List[Int], duplicate: (Int, Map[Int, Int])): Int = {
            l match {
                case Nil =>
                    val (count, _) = duplicate
                    count
                case head :: tail =>
                    val (count, result) = duplicate
                    if (result.contains(head)) inner(tail, (count + 1, result - head))
                    else inner(tail, (count, result + (head -> head)))
            }
        }
        inner(a.toList, (0, Map.empty))
    }
    
    def main(args: Array[String]) {
        val arr1: Array[Int] = Array(2, 2, 3, 3, 2, 2, 3)
        val arr2: Array[Int] = Array(10, 20, 30, 11, 11, 21)
        val arr3: Array[Int] = Array(10, 20, 30, 11, 11, 21, 21)
        
        print("\nThe element with odd occurrences in arr1 is: " + solution(arr1))
        print("\nThe element with odd occurrences in arr2 is: " + solution(arr2))
        print("\nThe element with odd occurrences in arr3 is: " + solution(arr3))
    }
}

Output

The element with odd occurrences in arr1 is: 3
The element with odd occurrences in arr2 is: 1
The element with odd occurrences in arr3 is: 2

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Scala program to create strings array... >>
<< Array Rotation in Scala...