Skip to content

Commit d803b21

Browse files
Merge pull request TheAlgorithms#1425 from gijsh21/mode
Create Mode.java
2 parents 35ccbd9 + bbe6f94 commit d803b21

1 file changed

Lines changed: 63 additions & 0 deletions

File tree

Maths/Mode.java

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package Maths;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.Collections;
6+
import java.util.HashMap;
7+
8+
/*
9+
* Find the mode of an array of numbers
10+
*
11+
* The mode of an array of numbers is the most frequently occurring number in the array,
12+
* or the most frequently occurring numbers if there are multiple numbers with the same frequency
13+
*/
14+
public class Mode {
15+
16+
public static void main(String[] args) {
17+
18+
/* Test array of integers */
19+
assert (mode(new int[]{})) == null;
20+
assert Arrays.equals(mode(new int[]{5}), new int[]{5});
21+
assert Arrays.equals(mode(new int[]{1, 2, 3, 4, 5}), new int[]{1, 2, 3, 4, 5});
22+
assert Arrays.equals(mode(new int[]{7, 9, 9, 4, 5, 6, 7, 7, 8}), new int[]{7});
23+
assert Arrays.equals(mode(new int[]{7, 9, 9, 4, 5, 6, 7, 7, 9}), new int[]{7, 9});
24+
25+
}
26+
27+
/*
28+
* Find the mode of an array of integers
29+
*
30+
* @param numbers array of integers
31+
* @return mode of the array
32+
*/
33+
public static int[] mode(int[] numbers) {
34+
35+
if(numbers.length == 0) return null;
36+
37+
HashMap<Integer, Integer> count = new HashMap<>();
38+
39+
for(int num : numbers) {
40+
if(count.containsKey(num)) {
41+
42+
count.put(num, count.get(num) + 1);
43+
44+
} else {
45+
46+
count.put(num, 1);
47+
48+
}
49+
50+
}
51+
52+
int max = Collections.max(count.values());
53+
ArrayList<Integer> modes = new ArrayList<>();
54+
55+
for(int num : count.keySet()) {
56+
if(count.get(num) == max) {
57+
modes.add(num);
58+
}
59+
}
60+
return modes.stream().mapToInt(n -> n).toArray();
61+
}
62+
63+
}

0 commit comments

Comments
 (0)