Scala Example program for odd occurrences in an array - Computer in Hindi | Business in Hindi

Sunday, February 14, 2021

Scala Example program for odd occurrences in an array

 यहां, हम एक ऐसा प्रोग्राम बनाएंगे, जो किसी odd elements in an array की घटनाओं को गिनेगा और विषम घटनाओं वाले तत्वों को लौटाएगा।

सरणियों में कई तत्व हैं और हम सरणी में विषम तत्वों की कुल संख्या की गणना करेंगे।

Scala Example Program

 

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

    Occurrence of 1 is 2 
    Occurrence of 5 is 3.

    Now, 5 has an odd occurrence.

अब, Array में विषम घटनाओं को खोजने के लिए एक प्रोग्राम देखते हैं,

Scala example Program for 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 : - 

Output Scala Program
Output Scala Example Program



No comments:

Post a Comment