Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement improvements in the modeArray method #208

Closed
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
}
Loading