Repository navigation
Expand file tree
/
Copy pathHashMap_Random.java
More file actions
73 lines (61 loc) · 1.77 KB
/
Copy pathHashMap_Random.java
File metadata and controls
73 lines (61 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// Java program to return index of most occurring element
// of the array randomly with equal probability
import java.util.*;
class HashMap_Random
{
// Function to return index of most occurring element
// of the array randomly with equal probability
static void findRandomIndexOfMax(int arr[], int n)
{
// freq store frequency of each element in the array
HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++)
if(mp.containsKey(arr[i]))
{
mp.put(arr[i], mp.get(arr[i]) + 1);
}
else
{
mp.put(arr[i], 1);
}
int max_element = Integer.MIN_VALUE; // stores max occurring element
// stores count of max occurring element
int max_so_far = Integer.MIN_VALUE;
// traverse each pair in map and find maximum
// occurring element and its frequency
for (Map.Entry<Integer, Integer> p : mp.entrySet())
{
if (p.getValue() > max_so_far)
{
max_so_far = p.getValue();
max_element = p.getKey();
}
}
// generate a random number between [1, max_so_far]
int r = (int) ((new Random().nextInt(max_so_far) % max_so_far) + 1);
// traverse array again and return index of rth
// occurrence of max element
for (int i = 0, count = 0; i < n; i++)
{
if (arr[i] == max_element)
count++;
// print index of rth occurrence of max element
if (count == r)
{
System.out.print("Element with maximum frequency present "
+"at index " + i +"\n");
break;
}
}
}
// Driver code
public static void main(String[] args)
{
// input array
int arr[] = { -1, 4, 9, 7, 7, 2, 7, 3, 0, 9, 6, 5,
7, 8, 9 };
int n = arr.length;
findRandomIndexOfMax(arr, n);
}
}
// This code is contributed by Rajput-Ji