Count the occurrence of array elements

Given a unsorted array of integers, Our goal is to count all occurring occurrences in this array by using hashing.

Count occurrences of array elements

Here given code implementation process.

// C++ Program 
// Count the occurrence of array elements
#include <iostream>
#include <map> // for map
using namespace std;

// Function which is display array elements
void display(int arr[], int size)
{
	for (int i = 0; i < size; ++i)
	{
		cout << "   " << arr[i];
	}
	cout << "\n";
}
// Count occurrence of given array
void occurrence(int arr[], int size)
{
  	// Display Array
  	display(arr,size);
  
	// Create a empty map
	map < int, int > mp;
	for (int i = 0; i < size; ++i)
	{
		// When key is already exists then incrementing the value by one
		// Or when key are not exist first creating a new element and set 0 that value. 
		// And increment its value   
		mp[arr[i]]++;
	}
  	cout <<" Occurrence "<<endl;
	map < int, int > ::iterator element;
	for (element = mp.begin(); element != mp.end(); ++element)
	{
		// Display elements occurrences
		cout <<"  "<< element->first << "  :  " << element->second << endl;
	}
}
int main()
{
	// Array element
	int arr[] = {
		1 , 3 , 2 , 1 , 4 , 2 , 7 , 9 , 1 , 3 , 3 , 4 , 7
	};
	// Get the size of array
	int size = sizeof(arr) / sizeof(arr[0]);
	occurrence(arr, size);
	return 0;
}

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
/*
  Java program
  Count the occurrence of array elements
*/
import java.util.HashMap;
import java.util.Map;
public class MyHashing
{
	//Function which is display array elements
	public static void display(int[] arr)
	{
		for (int i = 0; i < arr.length; ++i)
		{
			System.out.print("   " + arr[i]);
		}
		System.out.print("\n");
	}
	// Count occurrence of given array
	public static void occurrence(int[] arr)
	{
		// Display given array
		display(arr);
		// Create a empty map
		Map < Integer, Integer > map = new HashMap < > ();
		for (int i = 0; i < arr.length; i++)
		{
			if (map.containsKey(arr[i]))
			{
				// When key exists then update value
				map.put(arr[i], map.get(arr[i]) + 1);
			}
			else
			{
				map.put(arr[i], 1);
			}
		}
      	System.out.println("  Occurrence ");
		//  Display calculated result
		for (int key: map.keySet())
		{
			System.out.println("  "+key + "  :  " + map.get(key));
		}
	}
	public static void main(String[] args)
	{
		//Array element
		int[] arr = {
			1 , 3 , 2 , 1 , 4 , 2 , 7 , 9 , 1 , 3 , 3 , 4 , 7
		};
		occurrence(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
/*
  C# program
  Count the occurrence of array elements
*/
using System;
using System.Collections.Generic;
public class Hashing
{
  	//Function which is display array elements
	public static void display(int[] arr)
	{
		for (int i = 0; i < arr.Length; ++i)
		{
			Console.Write("   " + arr[i]);
		}
		Console.Write("\n");
	}
    // Count occurrence of given array
	public static void occurrence(int[] arr)
	{
      	// Display array elements
        display(arr);
      
		SortedDictionary < int, int > map = new SortedDictionary < int, int > ();
		
        for (int i = 0; i < arr.Length; i++)
		{
			if (map.ContainsKey(arr[i]))
			{
				// When key exists then update value
				map[arr[i]] = map[arr[i]] + 1;
			}
			else
			{
				map.Add(arr[i], 1);
			}
		}
      	Console.WriteLine("  Occurrence ");
      	
        //  Display calculated result
		foreach(KeyValuePair < int, int > entry in map)
		{
			Console.WriteLine("  " + entry.Key + "  :  " + entry.Value);
		}
	}
	public static void Main(String[] args)
	{
		//Array element
		int[] arr = {
			1 , 3 , 2 , 1 , 4 , 2 , 7 , 9 , 1 , 3 , 3 , 4 , 7
		};
		occurrence(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
<?php
/*
* PHP Program 
  Count the occurrence of array elements
*/
class MyHashing
{
    //Function which is display array elements
    public function display($arr)
    {
        for ($i = 0; $i < count($arr); $i++)
        {
            echo "  ". $arr[$i];
        }
    }
    // Count occurrence of given array
    public function occurrence($arr)
    {
        $this->display($arr);

        $size = count($arr);

        $dict_item = array();

        for ($i = 0; $i < $size; ++$i)
        {
            if (array_key_exists($arr[$i], $dict_item))
            {
                // When key exists then update value
                $dict_item[$arr[$i]] = $dict_item[$arr[$i]] + 1;
            }
            else
            {
                $dict_item[$arr[$i]] = 1;
            }
        }
        echo "\n Occurrence \n";
		ksort($dict_item);
        // Display occurrence of elements
        foreach($dict_item as $key => $value)
        {
            echo "  ".$key."  :  ".$value."\n";
        }
    }
}

function main()
{
    $task = new MyHashing();
    $arr = array(1, 3, 2, 1, 4, 2, 7, 9, 1, 3, 3, 4, 7);
    $task->occurrence($arr);
}
main();

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
//Node Js Program
//Count the occurrence of array elements
class Hashing
{
    //Function which is display array elements
    display(arr)
    {
        for (var i = 0; i < arr.length; ++i)
        {
            process.stdout.write("   " + arr[i]);
        }
        process.stdout.write("\n");
    }
    occurrence(arr)
    {
        this.display(arr);
        
        //Define empty map
        let map = new Map();

        for (var i = 0; i < arr.length; i++)
        {
            if (map.has(arr[i]))
            {
                //when key exist then put new key
                map.set(arr[i], map.get(arr[i]) + 1);
            }
            else
            {
                map.set(arr[i], 1);
            }
        }
        //Sort map by key
        map = new Map([...map.entries()].sort());
      	console.log(" Occurrence");
        //Display result
        for (let [key, value] of map.entries())
        {
            console.log("  "+ key + "  :  " + value);
        }
    }
}

function main()
{
    var obj = new Hashing();
    //Array element
    var arr = [1, 3, 2, 1, 4, 2, 7, 9, 1, 3, 3, 4, 7];
    obj.occurrence(arr);
}
main();

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
# Python program
# Count the occurrence of list elements

class MyHashing:

    # Function which is display list elements
    def display(self, list_data) :
        i = 0
        for x in list_data :
            print("  ",x, end ="")
        print(end = "\n")

    # Count occurrence of given list elements
    def occurrence(self,list_data):

        self.display(list_data);
        # Define empty dictionary
        dict_item = {}

        for key in list_data:
            if key in dict_item:
                # When key exists then update value
                dict_item[key] += 1
            else:
                # When gets a new key
                dict_item[key] = 1

        print("   Occurrence ")
        #  Display occurrence of elements        
        for key, value in dict_item.items():
            print("  ",key," : ",value)


def main():
    obj = MyHashing()
    # define list element
    item =[1,3,2,1,4,2,7,9,1,3,3,4,7]
    obj.occurrence(item)


if __name__=="__main__":
  main()

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
# Ruby program
# Count the occurrence of array elements

class MyHashing 
    # Function which is display array elements
    def display(arr, size) 
        i = 0
        while (i < size) 
            print("   ", arr[i])
            i += 1
        end

        print("\n")
    end  
    # Count occurrence of given array
    def occurrence(arr) 
        # Display array elements
        display(arr,arr.length)
        # Create new hash
        record = Hash.new 
        i = 0
        while (i < arr.length) 

            if (record.key?(arr[i])) 
                # When key exists then update value
                record[arr[i]] = record[arr[i]] + 1
            else
                # When gets a new key 
                record[arr[i]] = 1
            end

            i+=1
        end

        # Sort record by keys
        record=record.sort.to_h
        print(" Occurrence \n")
        # Display occurrence of elements  
        record.each{ |key,value|  puts "   #{key}  :  #{value}" }
    end
end
def main() 
    obj = MyHashing.new()
    # Array element
    arr = [1, 3, 2, 1, 4, 2, 7, 9, 1, 3, 3, 4, 7]
    obj.occurrence(arr)
end
main()

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
/*
    Scala Program
    Count the occurrence of array elements
*/
import scala.collection.immutable.ListMap

class MyHashing
{
    //Function which is display array elements
    def display(arr: Array[Int], size: Int): Unit = {
        var i: Int = 0;
        while (i < size)
        {
            print("   " + arr(i));
            i += 1;
        }
        print("\n");
    }
    //  Count occurrence of given array
    def occurrence(arr: Array[Int]): Unit = 
    {
        // Display array elements
        display(arr,arr.length);

        // Creating a empty Map 
        var map: Map[Int, Int] = Map();

        var i: Int = 0;

        while (i < arr.length)
        {
            if (map.contains(arr(i)))
            {
                // When key exists then update value
                map += (arr(i)->(map(arr(i)) + 1));
            }
            else
            {
                // new element into map
                map += (arr(i)->1);
            }
            i += 1;
        }

        //Sort map value by key
        val result = ListMap(map.toSeq.sortWith(_._1 < _._1): _ * )
        
        println("  Occurrence ");
        // Display occurrence of elements
        result.keys.foreach
        {
            key => println("  " + key + "  :  " + result(key))
        }
    }
}
object Main
{
    def main(args: Array[String]): Unit = {
        var obj: MyHashing = new MyHashing();
        //Array element
        var arr: Array[Int] = Array(1, 3, 2, 1, 4, 2, 7, 9, 1, 3, 3, 4, 7);
        obj.occurrence(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
// Swift 4 Program
// Count the occurrence of array elements
class Hashing
{
	//Function which is display array elements
	func display(_ arr: [Int], _ size: Int)
	{
		var i: Int = 0;
		while (i < size)
		{
			print("   ", arr[i], terminator: "");
			i += 1;
		}
		print(terminator: "\n");
	}
	// Count occurrence of given array
	func occurrence(_ arr: [Int])
	{
		display(arr, arr.count);
		var dict = [Int: Int]();
		var i = 0;
		var data = 0;
		while (i < arr.count)
		{
			if (dict.count > 0 && dict.keys.contains(arr[i]))
			{
				// When key exists then update value
				data = dict[arr[i]] ?? 1;
				data += 1;
				dict[arr[i]] = data;
			}
			else
			{
				// new element into dict
				dict[arr[i]] = 1;
			}
			i += 1;
		}
		print("  Occurrence ");
		// Display occurrence of elements
		for (k, v) in Array(dict).sorted(by: < )
		{
			print("  \(k)  :  \(v)")
		}
	}
}
func main()
{
	let obj: Hashing = Hashing();
	//Array element
	let arr: [Int] = [1, 3, 2, 1, 4, 2, 7, 9, 1, 3, 3, 4, 7];
	obj.occurrence(arr);
}
main();

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
/* 
  Kotlin Program
  Count the occurrence of array elements
*/
class MyHashing
{
    // Function which is display array elements
    fun display(arr: Array<Int>): Unit
    {
        for(value in arr)
        {
            print("  "+value);
        }
        print("\n");
    }
    // Count occurrence of given array
    fun occurrence(arr: Array<Int>): Unit
    {
        // Display Array
        display(arr);
        // Create a empty map
        val mp = mutableMapOf<Int, Int>();
        for (data in arr)
        {
            if (mp.containsKey(data))
            {
                var value: Int ? = mp.get(data);
                if (value != null)
                {
                    // When key already exists
                    mp.put(data, value + 1);
                }
            }
            else
            {
                mp.put(data, 1);
            }
        }
        println("  Occurrence ");
        // Display occurrence of elements
        for (key in mp.toSortedMap().keys)
        {
            println("   "+key+"  :  "+mp[key]);
        }
    }
}
fun main(args: Array<String>): Unit
{
    var task: MyHashing = MyHashing();
    // Define array of integer elements
    var arr: Array<Int> = arrayOf(1, 3, 2, 1, 4, 2, 7, 9, 1, 3, 3, 4, 7);
    task.occurrence(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







© 2021, kalkicode.com, All rights reserved