Finding the mode of all elements in an array
Hint: Suppose we have the following array of numbers: [2, 3, 4, 2, 5, 3, 4, 2, 3, 5, 5].
After iterating through the array, we will have a frequency map that looks like this:
{2=3, 3=3, 4=2, 5=3}
Therefore, the mode of the array [2, 3, 4, 2, 5, 3, 4, 2, 3, 5, 5] is {2, 3, 5}.
Here’s a Java program that finds the mode of all elements in an array:
import java.util.HashMap; import java.util.Map; public class ModeFinder { public static void main(String[] args) { int[] array = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4}; int mode = findMode(array); System.out.println("Mode: " + mode); } public static int findMode(int[] array) { if (array.length == 0) throw new IllegalArgumentException("Array must not be empty."); // Create a map to store the frequency of each element in the array Map<Integer, Integer> frequencyMap = new HashMap<>(); // Calculate the frequency of each element in the array for (int num : array) { frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); } int maxFrequency = 0; int mode = 0; // Find the element with the maximum frequency for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) { int frequency = entry.getValue(); if (frequency > maxFrequency) { maxFrequency = frequency; mode = entry.getKey(); } } return mode; } }
In this program, we define a `findMode` method that takes an integer array as input and returns the mode. We use a `HashMap` to store the frequency of each element in the array. Then, we iterate through the map entries to find the element with the maximum frequency, which represents the mode. Finally, the program prints the mode to the console.
In the `main` method, we provide an example array `{1, 2, 2, 3, 3, 3, 4, 4, 4, 4}` and call the `findMode` method to demonstrate its usage.