Skip to content

Commit d55e89d

Browse files
authored
refactor: Mode (#6381)
refactor: Mode
1 parent dcb02c6 commit d55e89d

File tree

1 file changed

+20
-17
lines changed
  • src/main/java/com/thealgorithms/maths

1 file changed

+20
-17
lines changed

src/main/java/com/thealgorithms/maths/Mode.java

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,46 +3,49 @@
33
import java.util.ArrayList;
44
import java.util.Collections;
55
import java.util.HashMap;
6+
import java.util.List;
7+
import java.util.Map;
68

7-
/*
8-
* Find the mode of an array of numbers
9-
*
10-
* The mode of an array of numbers is the most frequently occurring number in the array,
11-
* or the most frequently occurring numbers if there are multiple numbers with the same frequency
9+
/**
10+
* Utility class to calculate the mode(s) of an array of integers.
11+
* <p>
12+
* The mode of an array is the integer value(s) that occur most frequently.
13+
* If multiple values have the same highest frequency, all such values are returned.
14+
* </p>
1215
*/
1316
public final class Mode {
1417
private Mode() {
1518
}
1619

17-
/*
18-
* Find the mode of an array of integers
20+
/**
21+
* Computes the mode(s) of the specified array of integers.
22+
* <p>
23+
* If the input array is empty, this method returns {@code null}.
24+
* If multiple numbers share the highest frequency, all are returned in the result array.
25+
* </p>
1926
*
20-
* @param numbers array of integers
21-
* @return mode of the array
27+
* @param numbers an array of integers to analyze
28+
* @return an array containing the mode(s) of the input array, or {@code null} if the input is empty
2229
*/
2330
public static int[] mode(final int[] numbers) {
2431
if (numbers.length == 0) {
2532
return null;
2633
}
2734

28-
HashMap<Integer, Integer> count = new HashMap<>();
35+
Map<Integer, Integer> count = new HashMap<>();
2936

3037
for (int num : numbers) {
31-
if (count.containsKey(num)) {
32-
count.put(num, count.get(num) + 1);
33-
} else {
34-
count.put(num, 1);
35-
}
38+
count.put(num, count.getOrDefault(num, 0) + 1);
3639
}
3740

3841
int max = Collections.max(count.values());
39-
ArrayList<Integer> modes = new ArrayList<>();
42+
List<Integer> modes = new ArrayList<>();
4043

4144
for (final var entry : count.entrySet()) {
4245
if (entry.getValue() == max) {
4346
modes.add(entry.getKey());
4447
}
4548
}
46-
return modes.stream().mapToInt(n -> n).toArray();
49+
return modes.stream().mapToInt(Integer::intValue).toArray();
4750
}
4851
}

0 commit comments

Comments
 (0)