Finding the mode of a 2D array - java

I'm trying to return the mode of a 2D array using a frequency array. I have an array, score, which is of length 10, and has 3 columns. Each column contains an int that is between 0 and 100.
I'm trying to find a way that will iterate through the array and return the modal value. What I have so far is:
int value = 0;
int[] freq = new int[100];
for (int row = 0; row < score.length; row++) {
for (int col = 0; col < score[row].length; col++) {
score[row][col] = value;
freq[value]++;
}
}
int largest = 0;
int mode = -1;
for (int i = 0; i < 100; i++) {
if (freq[i] > largest)
{
largest = freq[i];
mode = i;
}
}
System.out.println("modal score is: " +mode);
Problem is that this is just returning the modal score as 0, which it isn't.

You have a problem on generating the freq array. If I understand correctly, on the first double-for block you are trying to put the frequencies of the numbers inside the freq array.
But all you do is:
int value = 0;
.....
score[row][col] = value;
freq[value]++;`
firstly you are changing the score array,( which is a problem for you I guess...) and the you go to freq[0] and do ++. Obviously modal is 0, that number appears in all of the array.
SOLUTION: in the first double for block you should do:
value = score[row][col];
freq[value]++;
so I think you mixed up the order of the line, it should be the other way around.

private static void printMode(double[][] doubles) {
HashMap<Double , Double> map = new HashMap();
for (int i = 0; i < doubles.length; i++) {
for (int j = 0; j < doubles[i].length; j++) {
double temp = doubles[i][j];
if(map.get(temp)==null){
map.put(doubles[i][j],1.0);
}else {
double temp2 = (double) map.get(temp);
map.put(doubles[i][j],++temp2);
}
}
}
Object[] objects = map.values().stream().sorted().toArray();
Stream stream = map.entrySet().stream().filter(val-> val.getValue().equals(objects[objects.length-1]));
stream.forEach(System.out::println);
}
I think using Stream for finding mode is the best way.
use int instead of double doesn't cause any problems.

int value = 0;
int [] freq = new int [arr.length];
for (int i = 0; i < arr.length; i++){
for (int j = 0; j < arr[i].length; j++){
value = arr[i][j];
freq[value]++;
}
}
int largest = 0;
int mode = 0;
for (int i = 0; i < freq.length; i++) {
if (freq[i] > largest)
{
largest = freq[i];
mode = i;
}
}
System.out.println("modal score is: " +mode);

Related

Find Special elements in a m*n matrix

My question is about to find the distinct number of positional elements in an m*n matrix which are either the minimum or maximum in their corresponding row or column. Below is my piece of code.
static void findSpecialElement(int[][] matrix)
{
for (int i = 0; i < matrix.length; i++)
{
int rowMin = matrix[i][0];
int colIndex = 0;
boolean specialElement = true;
for (int j = 1; j < matrix[i].length; j++)
{
if(matrix[i][j] < rowMin)
{
rowMin = matrix[i][j];
colIndex = j;
}
}
for (int j = 0; j < matrix.length; j++)
{
if(matrix[j][colIndex] > rowMin)
{
specialElement = false;
break;
}
}
if(specialElement)
{
System.out.println("Special Element is : "+rowMin);
}
}
}
For e.g: Given a matrix of size 3*3, the elements are stored as follows
1 3 4
5 2 9
8 7 6
The expected output is 7
Leaving 5 and 3 all other numbers in the matrix have either min or max in row and column.So, 7 out of 9 numbers have min or max values.
Then 7 is the output
Please return -1, if any row or any column has multiple minimum or maximum elements...
My error is am failing to get the expected answer 7 as per the question.
Probably you are looking for this-
#include <bits/stdc++.h>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
vector<string> split(const string &);
// Complete the countSpecialElements function below.
int countSpecialElements(vector<vector<int>> matrix) {
int m = matrix.size(); //rows
int n = matrix[0].size(); //columns
int maxrow[102] , minrow[102];
int maxcol[102], mincol[102];
for(int p=0;p<102;p++){
maxrow[p] =0 ;
maxcol[p] = 0;
minrow[p]=0;
mincol[p]=0;
}
int k=0;
int i,j;
for(i=0;i<m;i++){
int rminn = INT_MAX;
int rmaxx = INT_MIN;
for(j=0;j<n;j++){
if(matrix[i][j]==rmaxx || matrix[i][j]==rminn) return -1;
if(matrix[i][j] > rmaxx ) rmaxx = matrix[i][j];
if(matrix[i][j] < rminn) rminn = matrix[i][j];
}
maxrow[i] = rmaxx;
minrow[i] = rminn;
for(j=0;j<n;j++){
int cminn = INT_MAX;
int cmaxx = INT_MIN;
for(int p=0;p<m;p++){
if(matrix[p][j]== cmaxx || matrix[p][j] == cminn) return -1;
if(matrix[p][j] > cmaxx ) cmaxx = matrix[p][j];
if(matrix[p][j] < cminn) cminn = matrix[p][j];
}
maxcol[j] = cmaxx;
mincol[j] = cminn;
}
}
int cnt = 0;
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
if((matrix[i][j]== maxrow[i])||(matrix[i][j]==minrow[i])||(matrix[i][j]==maxcol[j])||(matrix[i][j]==mincol[j]))
cnt++;
}
}
return cnt;
}
Based on updates, I think that your problem can be simplified as: Count the items who are min or max in a row or column. If that's ok, your algorithm is wrong because:
You're checking the min in column and row (in both at he same time)
You're not checking the max
You're printing the number found
So, your strategy should be something like:
create a counter in zero
for every item in matrix
check if is min in his row
check if is max in his row
check if is min in his column
check if is max in his column
if one check is ok, increase counter
print or return the counter
That should help you.
int maxNum = matrix[0][0]; int minNum = matrix[0][0];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if(maxNum < matrix[i][j]){
maxNum = matrix[i][j];
}
else if (minNum > matrix[i][j]) {
minNum = matrix[i][j];
}
}
}
I think it can be done in better=faster way but my O(n^2):
import java.util.HashSet;
import java.util.Set;
public class Main {
public static int[][] input = {
{1, 3, 4},
{5, 2, 9},
{8, 7, 6}
};
public static void main(String[] args) {
int numberOfElements = 0;
Set<Integer> numberOfUniqueElements = new HashSet<>();
Set<Integer> specialElements = new HashSet<Integer>();
for (int i = 0; i < input.length; i++) {
int maxInRow = Integer.MIN_VALUE;
int minInRow = Integer.MAX_VALUE;
int maxInColumn = Integer.MIN_VALUE;
int minInColumn = Integer.MAX_VALUE;
for (int j = 0; j < input[i].length; j++) {
numberOfElements++;
numberOfUniqueElements.add(input[i][j]);
if (input[i][j] > maxInRow) {
maxInRow = input[i][j];
}
if (input[i][j] < minInRow) {
minInRow = input[i][j];
}
if (input[j][i] > maxInColumn) {
maxInColumn = input[j][i];
}
if (input[j][i] < minInColumn) {
minInColumn = input[j][i];
}
}
specialElements.add(minInRow);
specialElements.add(maxInRow);
specialElements.add(minInColumn);
specialElements.add(maxInColumn);
}
if (numberOfUniqueElements.size() != numberOfElements) {
System.out.println("-1");
} else {
System.out.println(specialElements.size());
}
}
}

JAVA - Compare two arrays and create a new array with only the unique values from the first

I have to solve an exercise with the following criteria:
Compare two arrays:
int[] a1 = {1, 3, 7, 8, 2, 7, 9, 11};
int[] a2 = {3, 8, 7, 5, 13, 5, 12};
Create a new array int[] with only unique values from the first array. Result should look like this: int[] result = {1,2,9,11};
NOTE: I am not allowed to use ArrayList or Arrays class to solve this task.
I'm working with the following code, but the logic for the population loop is incorrect because it throws an out of bounds exception.
public static int[] removeDups(int[] a1, int[] a2) {
//count the number of duplicate values found in the first array
int dups = 0;
for (int i = 0; i < a1.length; i++) {
for (int j = 0; j < a2.length; j++) {
if (a1[i] == a2[j]) {
dups++;
}
}
}
//to find the size of the new array subtract the counter from the length of the first array
int size = a1.length - dups;
//create the size of the new array
int[] result = new int[size];
//populate the new array with the unique values
for (int i = 0; i < a1.length; i++) {
int count = 0;
for (int j = 0; j < a2.length; j++) {
if (a1[i] != a2[j]) {
count++;
if (count < 2) {
result[i] = a1[i];
}
}
}
}
return result;
}
I would also love how to solve this with potentially one loop (learning purposes).
I offer following soulution.
Iterate over first array, and find out min and max it's value.
Create temporary array with length max-min+1 (you could use max + 1 as a length, but it could follow overhead when you have values e.g. starting from 100k).
Iterate over first array and mark existed values in temorary array.
Iterate over second array and unmark existed values in temporary array.
Place all marked values from temporary array into result array.
Code:
public static int[] getUnique(int[] one, int[] two) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i = 0; i < one.length; i++) {
min = one[i] < min ? one[i] : min;
max = one[i] > max ? one[i] : max;
}
int totalUnique = 0;
boolean[] tmp = new boolean[max - min + 1];
for (int i = 0; i < one.length; i++) {
int offs = one[i] - min;
totalUnique += tmp[offs] ? 0 : 1;
tmp[offs] = true;
}
for (int i = 0; i < two.length; i++) {
int offs = two[i] - min;
if (offs < 0 || offs >= tmp.length)
continue;
if (tmp[offs])
totalUnique--;
tmp[offs] = false;
}
int[] res = new int[totalUnique];
for (int i = 0, j = 0; i < tmp.length; i++)
if (tmp[i])
res[j++] = i + min;
return res;
}
For learning purposes, we won't be adding new tools.
Let's follow the same train of thought you had before and just correct the second part:
// populate the new array with the unique values
for (int i = 0; i < a1.length; i++) {
int count = 0;
for (int j = 0; j < a2.length; j++) {
if (a1[i] != a2[j]) {
count++;
if (count < 2) {
result[i] = a1[i];
}
}
}
}
To this:
//populate the new array with the unique values
int position = 0;
for (int i = 0; i < a1.length; i++) {
boolean unique = true;
for (int j = 0; j < a2.length; j++) {
if (a1[i] == a2[j]) {
unique = false;
break;
}
}
if (unique == true) {
result[position] = a1[i];
position++;
}
}
I am assuming the "count" that you implemented was in attempt to prevent false-positive added to your result array (which would go over). When a human determines whether or not an array contains dups, he doesn't do "count", he simply compares the first number with the second array by going down the list and then if he sees a dup (a1[i] == a2[j]), he would say "oh it's not unique" (unique = false) and then stop going through the loop (break). Then he will add the number to the second array (result[i] = a1[i]).
So to combine the two loops as much as possible:
// Create a temp Array to keep the data for the loop
int[] temp = new int[a1.length];
int position = 0;
for (int i = 0; i < a1.length; i++) {
boolean unique = true;
for (int j = 0; j < a2.length; j++) {
if (a1[i] == a2[j]) {
unique = false;
break;
}
}
if (unique == true) {
temp[position] = a1[i];
position++;
}
}
// This part merely copies the temp array of the previous size into the proper sized smaller array
int[] result = new int[position];
for (int k = 0; k < result.length; k++) {
result[k] = temp[k];
}
Making your code work
Your code works fine if you correct the second loop. Look at the modifications I did:
//populate the new array with the unique values
int counter = 0;
for (int i = 0; i < a1.length; i++) {
for (int j = 0; j < a2.length; j++) {
if (a1[i] == a2[j]) {
result[counter] = a1[i];
counter++;
}
}
}
The way I would do it
Now, here is how I would create a method like this without the need to check for the duplicates more than once. Look below:
public static int[] removeDups(int[] a1, int[] a2) {
int[] result = null;
int size = 0;
OUTERMOST: for(int e1: a1) {
for(int e2: a2) {
if(e1 == e2)
continue OUTERMOST;
}
int[] temp = new int[++size];
if(result != null) {
for(int i = 0; i < result.length; i++) {
temp[i] = result[i];
}
}
temp[temp.length - 1] = e1;
result = temp;
}
return result;
}
Instead of creating the result array with a fixed size, it creates a new array with the appropriate size everytime a new duplicate is found. Note that it returns null if a1 is equal a2.
You can make another method to see if an element is contained in a list :
public static boolean contains(int element, int array[]) {
for (int iterator : array) {
if (element == iterator) {
return true;
}
}
return false;
}
Your main method will iterate each element and check if it is contained in the second:
int[] uniqueElements = new int[a1.length];
int index = 0;
for (int it : a1) {
if (!contains(it, a2)) {
uniqueElements[index] = it;
index++;
}
}

Radix Sort an array of strings using a queue in Java

I don't completely understand radix sort so that is making this more difficult for me to write this program. I need to sort an array of strings that is read from a .txt file. I was able to read the file and enter the strings into an array. A string can contain letters or special characters. I need help with writing the code for sorting the array. It feels like I'm close to the having the correct code, but I'm stuck and don't know what else to do. It would be greatly appreciated if I could get help and point me in the right direction.
Each string has the same amount of characters. I am also using a stackPackage that contains a queue class. I need to modify the code the my professor gave me to sort strings.
Here is the code I started with:
import queuepackage.*;
public class Radix {
public static void main(String[] args) {
int[] array = {143,934,782,687,555,222,111,213,842,2000};
printArray(array);
radixSort(array, 1000);
printArray(array);
}
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + ", ");
}
System.out.println();
}
public static void radixSort(int[] array, int maxPowerOf10) {
Queue[] queueArray = new Queue[10];
for (int queueNum = 0; queueNum < 10; queueNum++) {
queueArray[queueNum] = new Queue();
}
for (int powerOf10 = 1; powerOf10 <= maxPowerOf10; powerOf10 = powerOf10 * 10) {
for (int item = 0; item < array.length; item++) {
int digit = getDigit(array[item], powerOf10);
queueArray[digit].enqueue(new Integer(array[item]));
}
int item = 0;
for (int queueNum = 0; queueNum < 10; queueNum++) {
while (!queueArray[queueNum].isEmpty()) {
array[item] = ((Integer) queueArray[queueNum].dequeue()).intValue();
item++;
}
}
}
}
public static int getDigit(int number, int powerOf10) {
return (number/powerOf10)%10;
}
}
This is what I have.
length = length of the array
wordLen = length of a string in the array
Here is my current code of the radixSort method:
public static void radixSort(String[] array, int length, int wordLen) {
Queue[] queueArray = new Queue[256];
for (int queueNum = 0; queueNum < 256; queueNum++) {
queueArray[queueNum] = new Queue();
}
for (int len = 0; len < wordLen; len++) {
for (int item = 0; item < length; item++) {
int letter = array[item].charAt(len);
queueArray[letter].enqueue(new String(array[item]));
}
int item = 0;
for (int queueNum = 0; queueNum < 256; queueNum++) {
while (!queueArray[queueNum].isEmpty()) {
array[item] = ((String) queueArray[queueNum].dequeue()).toString();
item++;
}
}
}
}
It's almost working, you just need to iterate the word backwards, look at the second for loop
public static void radixSort(String[] array, int length, int wordLen) {
Queue[] queueArray = new Queue[256];
for (int queueNum = 0; queueNum < 256; queueNum++) {
queueArray[queueNum] = new Queue();
}
for (int len = wordLen-1; len >= 0; len--) {
for (int item = 0; item < length; item++) {
int letter = array[item].charAt(len);
queueArray[letter].enqueue(new String(array[item]));
}
int item = 0;
for (int queueNum = 0; queueNum < 256; queueNum++) {
while (!queueArray[queueNum].isEmpty()) {
array[item] = ((String) queueArray[queueNum].dequeue()).toString(); // Here you need to swap the
item++;
}
}
}
}
If you iterate it in the regular way you are losing the previous information, so the last characters are the most important
Good luck!
The only mistake in your code that I can see is that in RadixSort you wanna start with sorting by the least significant digit and move up to more significant digits as you go. In this case however you are starting at the left and going right which is the wrong way around for natural order String sorting.
This however can be easily fixed by changing for (int len = 0; len < wordLen; len++) into for (int len = wordLen - 1; len >= 0; len--).
Changing for (int len = 0; len < wordLen; len++) into for (int len = wordLen - 1; len >= 0; len--) worked and makes my program does what it is supposed to

Insert integers into 2d array

private void enterbtnActionPerformed(java.awt.event.ActionEvent evt) {
int [][] array = new int [4][4]; // my array
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
array[i][j]= ;// use for feeding the code
}
popfield.setText(Arrays.deepToString( array ) );
}
I want to insert integers into 2d array via 2 textfields one for columns and one for rows elements via two text fields xfield and yfield
So.. For create 2D int array:
//int 2 dimensional array
int[][] array = null;
//your fields values
final int xFieldVal = 5;
final int yFieldVal = 7;
//values to fill into array
final int minArrayVal = 50;
final int maxArrayVal = 100;
//create matrix / grid with dimensions (xFieldVal x yFieldVal)
array = new int[xFieldVal][yFieldVal];
(that creates recangle xFieldVal x yFieldVal- or Y*X..)
While you have rectangle array you can acces to all value for filling eg. like that:
//random generator
Random rnd = new Random();
for (int i = 0; i < xFieldVal; i++) {
for (int j = 0; j < yFieldVal; j++) {
//generate new int in interval
array[i][j] = minArrayVal + rnd.nextInt(maxArrayVal- minArrayVal+ 1);
}
}
While you will dont have rectangle array (you can have eg. just 1st dimension fixed, and 2nd not- I mean each "row" can have difference "columns" count), you have to use that loop:
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
//printing next line
System.out.println();
}
Eg. to find min and max value, you can use that:
//set on the max possible (every value should be less than that)
int min=Integer.MAX_VALUE;
//set on the min possible (every value should be more than that)
int max=Integer.MIN_VALUE;
//iteration through 1st index (eg. iteration through rows)
for (int i = 0; i < array.length; i++) {
//iteration through 2nd index of 1st index (eg. through all columns)
for (int j = 0; j < array[i].length; j++) {
//compare and assign if array value is less than actual found min
if(min > array[i][j]){
min = array[i][j];
}
//compare and assign if array value is more than actual found max
if(max < array[i][j]){
max = array[i][j];
}
}
}
I dont think you understand what a 2D array is
think of it as a grid. you insert into a single cell at a time.
a single cell belongs to a row and a column hence has a row number and column number...like an excel work book? cell b5?
so if you want to input numbers all you gotta do is have a single textfield lets call it txt
the rest is as follows
private void enterbtnActionPerformed(java.awt.event.ActionEvent evt)
{
int [][] array = new int [4][4]; // my array
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
array[i][j]= Integer.parseInt(txt.getText());// use for feeding the code
}
popfield.setText(Arrays.deepToString( array ) );
}

Finding multiple modes in an array of integers with 1000 elements

So I need a way to find the mode(s) in an array of 1000 elements, with each element generated randomly using math.Random() from 0-300.
int[] nums = new int[1000];
for(int counter = 0; counter < nums.length; counter++)
nums[counter] = (int)(Math.random()*300);
int maxKey = 0;
int maxCounts = 0;
sortData(array);
int[] counts = new int[301];
for (int i = 0; i < array.length; i++)
{
counts[array[i]]++;
if (maxCounts < counts[array[i]])
{
maxCounts = counts[array[i]];
maxKey = array[i];
}
}
This is my current method, and it gives me the most occurring number, but if it turns out that something else occurred the same amount of times, it only outputs one number and ignore the rest.
WE ARE NOT ALLOWED TO USE ARRAYLIST or HASHMAP (teacher forbade it)
Please help me on how I can modify this code to generate an output of array that contains all the modes in the random array.
Thank you guys!
EDIT:
Thanks to you guys, I got it:
private static String calcMode(int[] array)
{
int[] counts = new int[array.length];
for (int i = 0; i < array.length; i++) {
counts[array[i]]++;
}
int max = counts[0];
for (int counter = 1; counter < counts.length; counter++) {
if (counts[counter] > max) {
max = counts[counter];
}
}
int[] modes = new int[array.length];
int j = 0;
for (int i = 0; i < counts.length; i++) {
if (counts[i] == max)
modes[j++] = array[i];
}
toString(modes);
return "";
}
public static void toString(int[] array)
{
System.out.print("{");
for(int element: array)
{
if(element > 0)
System.out.print(element + " ");
}
System.out.print("}");
}
Look at this, not full tested. But I think it implements what #ajb said:
private static int[] computeModes(int[] array)
{
int[] counts = new int[array.length];
for (int i = 0; i < array.length; i++) {
counts[array[i]]++;
}
int max = counts[0];
for (int counter = 1; counter < counts.length; counter++) {
if (counts[counter] > max) {
max = counts[counter];
}
}
int[] modes = new int[array.length];
int j = 0;
for (int i = 0; i < counts.length; i++) {
if (counts[i] == max)
modes[j++] = array[i];
}
return modes;
}
This will return an array int[] with the modes. It will contain a lot of 0s, because the result array (modes[]) has to be initialized with the same length of the array passed. Since it is possible that every element appears just one time.
When calling it at the main method:
public static void main(String args[])
{
int[] nums = new int[300];
for (int counter = 0; counter < nums.length; counter++)
nums[counter] = (int) (Math.random() * 300);
int[] modes = computeModes(nums);
for (int i : modes)
if (i != 0) // Discard 0's
System.out.println(i);
}
Your first approach is promising, you can expand it as follows:
for (int i = 0; i < array.length; i++)
{
counts[array[i]]++;
if (maxCounts < counts[array[i]])
{
maxCounts = counts[array[i]];
maxKey = array[i];
}
}
// Now counts holds the number of occurrences of any number x in counts[x]
// We want to find all modes: all x such that counts[x] == maxCounts
// First, we have to determine how many modes there are
int nModes = 0;
for (int i = 0; i < counts.length; i++)
{
// increase nModes if counts[i] == maxCounts
}
// Now we can create an array that has an entry for every mode:
int[] result = new int[nModes];
// And then fill it with all modes, e.g:
int modeCounter = 0;
for (int i = 0; i < counts.length; i++)
{
// if this is a mode, set result[modeCounter] = i and increase modeCounter
}
return result;
THIS USES AN ARRAYLIST but I thought I should answer this question anyways so that maybe you can use my thought process and remove the ArrayList usage yourself. That, and this could help another viewer.
Here's something that I came up with. I don't really have an explanation for it, but I might as well share my progress:
Method to take in an int array, and return that array with no duplicates ints:
public static int[] noDups(int[] myArray)
{
// create an Integer list for adding the unique numbers to
List<Integer> list = new ArrayList<Integer>();
list.add(myArray[0]); // first number in array will always be first
// number in list (loop starts at second number)
for (int i = 1; i < myArray.length; i++)
{
// if number in array after current number in array is different
if (myArray[i] != myArray[i - 1])
list.add(myArray[i]); // add it to the list
}
int[] returnArr = new int[list.size()]; // create the final return array
int count = 0;
for (int x : list) // for every Integer in the list of unique numbers
{
returnArr[count] = list.get(count); // add the list value to the array
count++; // move to the next element in the list and array
}
return returnArr; // return the ordered, unique array
}
Method to find the mode:
public static String findMode(int[] intSet)
{
Arrays.sort(intSet); // needs to be sorted
int[] noDupSet = noDups(intSet);
int[] modePositions = new int[noDupSet.length];
String modes = "modes: no modes."; boolean isMode = false;
int pos = 0;
for (int i = 0; i < intSet.length-1; i++)
{
if (intSet[i] != intSet[i + 1]) {
modePositions[pos]++;
pos++;
}
else {
modePositions[pos]++;
}
}
modePositions[pos]++;
for (int modeNum = 0; modeNum < modePositions.length; modeNum++)
{
if (modePositions[modeNum] > 1 && modePositions[modeNum] != intSet.length)
isMode = true;
}
List<Integer> MODES = new ArrayList<Integer>();
int maxModePos = 0;
if (isMode) {
for (int i = 0; i< modePositions.length;i++)
{
if (modePositions[maxModePos] < modePositions[i]) {
maxModePos = i;
}
}
MODES.add(maxModePos);
for (int i = 0; i < modePositions.length;i++)
{
if (modePositions[i] == modePositions[maxModePos] && i != maxModePos)
MODES.add(i);
}
// THIS LIMITS THERE TO BE ONLY TWO MODES
// TAKE THIS IF STATEMENT OUT IF YOU WANT MORE
if (MODES.size() > 2) {
modes = "modes: no modes.";
}
else {
modes = "mode(s): ";
for (int m : MODES)
{
modes += noDupSet[m] + ", ";
}
}
}
return modes.substring(0,modes.length() - 2);
}
Testing the methods:
public static void main(String args[])
{
int[] set = {4, 4, 5, 4, 3, 3, 3};
int[] set2 = {4, 4, 5, 4, 3, 3};
System.out.println(findMode(set)); // mode(s): 3, 4
System.out.println(findMode(set2)); // mode(s): 4
}
There is a logic error in the last part of constructing the modes array. The original code reads modes[j++] = array[i];. Instead, it should be modes[j++] = i. In other words, we need to add that number to the modes whose occurrence count is equal to the maximum occurrence count

Categories

Resources