Skip to content

Commit

Permalink
Implement improvements in the modeArray method
Browse files Browse the repository at this point in the history
This commit implements significant improvements in the modeArray method to enhance its efficiency and handle cases of multiple modes or the absence of number repetition. I have optimized the calculation of the frequency of each element, updated the algorithm to find the maximum frequency value, and added handling to correctly build the array of modes. Additionally, I have added comments to document the changes made in the code and improve its readability
  • Loading branch information
GerardluqueDev committed May 7, 2024
1 parent 1494916 commit fda920a
Showing 1 changed file with 43 additions and 23 deletions.
66 changes: 43 additions & 23 deletions src/main/java/array/ArrayModeSnippet.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,34 +24,54 @@

package array;

import java.util.Arrays;

/**
* ArrayModeSnippet.
*/
public class ArrayModeSnippet {

/**
* Returns the mode of the array.
*
* @param arr array to find mode in it
* @return mode of array
*/
public static int modeArray(int[] arr) {
int mode = 0;
int maxcount = 0;

for (int i = 0; i < arr.length; i++) {
int count = 0;

for (int j = 0; j < arr.length; j++) {
if (arr[i] == arr[j]) {
count++;
/**
* Returns the mode(s) of the array.
* <p>
* This method finds the mode(s) of the input array, handling cases where there may be multiple modes or no repetition of numbers.
*
* @param arr the array to find mode(s) in
* @return an array containing the mode(s) of the input array
*/

public static int[] modeArray(int[] arr) {
// Find the maximum number in the array
int maxNumber = Arrays.stream(arr).max().orElse(0);

// Array to store the frequency of each element
int[] frequency = new int[maxNumber + 1];

// Calculate the frequency of each element
for (int num : arr) {
frequency[num]++;
}

// Find the maximum frequency value
int maxFrequency = Arrays.stream(frequency).max().orElse(0);

// Count the number of modes
int modesCount = 0;
for (int freq : frequency) {
if (freq == maxFrequency) {
modesCount++;
}
}
}
if (count > maxcount) {
maxcount = count;
mode = arr[i];
}

// Build the array of modes
int[] modes = new int[modesCount];
int index = 0;
for (int i = 0; i < frequency.length; i++) {
if (frequency[i] == maxFrequency) {
modes[index++] = i;
}
}

return modes;
}
return mode;
}
}

0 comments on commit fda920a

Please sign in to comment.