Find the frequency of each element in an array in scala
Scala program for Find the frequency of each element in an array. Here more information.
import scala.collection.mutable._;
class Occurrence()
{
// Function which is display array elements
def display(arr: Array[Int]): Unit = {
var i: Int = 0;
while (i < arr.length)
{
print(" " + arr(i));
i += 1;
}
print("\n");
}
// Count occurrence of given array
def frequency(arr: Array[Int]): Unit = {
// Display given array
display(arr);
// Create a empty map
var map: HashMap[Int, Int] = new HashMap[Int, Int]();
var i: Int = 0;
while (i < arr.length)
{
if (map.contains(arr(i)))
{
// When key exists then update value
map.addOne(arr(i), map.get(arr(i)).get + 1);
}
else
{
// Add new element
map.addOne(arr(i), 1);
}
i += 1;
}
println(" Occurrence ");
// Display calculated result
for ((key, value) <- map)
{
println(" " + key + " : " + value);
}
}
}
object Main
{
def main(args: Array[String]): Unit = {
// Array element
var arr: Array[Int] = Array(1, 3, 2, 1, 4, 2, 7, 9, 1, 3, 3, 4, 7);
var task: Occurrence = new Occurrence();
task.frequency(arr);
}
}
Output
1 3 2 1 4 2 7 9 1 3 3 4 7
Occurrence
1 : 3
2 : 2
3 : 3
4 : 2
7 : 2
9 : 1
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment