Scala program to find the odd occurrences in an array

Scala array program/example: Here, we will be creating a Scala program to find the odd occurrences in an array.
Submitted by Shivang Yadav, on April 05, 2020 [Last updated : March 10, 2023]

Scala – Odd Occurrences in an Array

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.

Now, let see a program to find the odd occurrences in Array,

Scala code to find the odd occurrences in an 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

Scala Array Programs »



Related Programs



All Scala Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.