forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Count Frequency Of Elemets In Java Fixex jainaman224#1601
Fixes jainaman224#1601
- Loading branch information
1 parent
b595add
commit 6e242f4
Showing
1 changed file
with
60 additions
and
0 deletions.
There are no files selected for viewing
60 changes: 60 additions & 0 deletions
60
Freq_Of_Elements_Of_Array/CountFrequencyOfArrayElements.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
import java.util.HashMap; | ||
import java.util.Scanner; | ||
|
||
|
||
/*Problem Statement | ||
* Given an array of elements count the frequency of every element in the array. | ||
*/ | ||
|
||
public class CountFrequencyOfArrayElements { | ||
|
||
public static void main(String[] args) { | ||
Scanner sc = new Scanner(System.in); | ||
|
||
//input size of array | ||
int n = sc.nextInt(); | ||
|
||
//input array | ||
int a[] = new int[n]; | ||
for(int i = 0; i < n; i++) | ||
a[i] = sc.nextInt(); | ||
|
||
countFreq(a, n); | ||
sc.close(); | ||
} | ||
|
||
private static void countFreq(int[] a, int n) { | ||
HashMap<Integer, Integer> hm = new HashMap<>(); // using hashmap to store the freq | ||
|
||
for(int i = 0; i < n; i++) | ||
{ | ||
if( hm.containsKey(a[i]) ) | ||
hm.put( a[i], hm.get(a[i]) + 1); | ||
else | ||
hm.put(a[i], 1); | ||
} | ||
|
||
//display the frequencies | ||
System.out.println("Element \t Frequency"); | ||
hm.forEach( | ||
(k,v) -> | ||
{ | ||
System.out.println(k+" \t\t "+v); | ||
} | ||
); | ||
} | ||
|
||
} | ||
|
||
/* | ||
* Input : | ||
5 | ||
2 1 1 6 1 | ||
* Output : | ||
Element Frequency | ||
1 3 | ||
2 1 | ||
6 1 | ||
* */ |