Home » Scala » Scala array programs

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

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,

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.