The question goes:
Write a method called mode that returns the most frequently occurring element of an array of integers. Assume that the array has at le
This is not the most fastest method around the block, but is fairly simple to understand if you don't wanna involve yourself in HashMaps and also want to avoid using 2 for loops for complexity issues....
int mode(int n, int[] ar) {
int personalMax=1,totalMax=0,maxNum=0;
for(int i=0;i<n-1;i++)
{
if(ar[i]==ar[i+1])
{
personalMax++;
if(totalMax<personalMax)
{
totalMax=personalMax;
maxNum=ar[i];
}
}
else
{
personalMax=1;
}
}
return maxNum;
}
public int mode(int[] array) {
int mode = array[0];
int maxCount = 0;
for (int i = 0; i < array.length; i++) {
int value = array[i];
int count = 1;
for (int j = 0; j < array.length; j++) {
if (array[j] == value) count++;
if (count > maxCount) {
mode = value;
maxCount = count;
}
}
}
return mode;
}
Based on the answer from @codemania23 and the Java Docs for HashMap I wrote this code snipped and tests of a method that returns the most occurrent number in an array of numbers.
import java.util.HashMap;
public class Example {
public int mostOcurrentNumber(int[] array) {
HashMap<Integer, Integer> map = new HashMap<>();
int result = -1, max = 1;
for (int arrayItem : array) {
if (map.putIfAbsent(arrayItem, 1) != null) {
int count = map.get(arrayItem) + 1;
map.put(arrayItem, count);
if (count > max) {
max = count;
result = arrayItem;
}
}
}
return result;
}
}
Unit Tests
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
public class ExampleTest extends Example {
@Test
public void returnMinusOneWhenInputArrayIsEmpty() throws Exception {
int[] array = new int[0];
assertEquals(mostOcurrentNumber(array), -1);
}
@Test
public void returnMinusOneWhenElementsUnique() {
int[] array = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
assertEquals(-1, mostOcurrentNumber(array));
}
@Test
public void returnOne() throws Exception {
int[] array = new int[]{0, 1, 0, 0, 1, 1, 1};
assertEquals(1, mostOcurrentNumber(array));
}
@Test
public void returnFirstMostOcurrentNumber() throws Exception {
int[] array = new int[]{0, 1, 0, 1, 0, 0, 1, 1};
assertEquals(0, mostOcurrentNumber(array));
}
}
check this.. Brief:Pick each element of array and compare it with all elements of the array, weather it is equal to the picked on or not.
int popularity1 = 0;
int popularity2 = 0;
int popularity_item, array_item; //Array contains integer value. Make it String if array contains string value.
for(int i =0;i<array.length;i++){
array_item = array[i];
for(int j =0;j<array.length;j++){
if(array_item == array[j])
popularity1 ++;
{
if(popularity1 >= popularity2){
popularity_item = array_item;
popularity2 = popularity1;
}
popularity1 = 0;
}
//"popularity_item" contains the most repeted item in an array.
THIS CODE CALCULATES MODE, MEDIAN, AND MEAN. IT IS TESTED AND IT DOES WORK. It is a complete program from start to finish and will compile.
import java.util.Arrays;
import java.util.Random;
import java.math.*;
/**
*
* @author Mason
*/
public class MODE{
public static void main(String args[])
{
System.out.print("Enter the quantity of random numbers ===>> ");
int listSize = Expo.enterInt();
System.out.println();
ArrayStats intStats = new ArrayStats(listSize);
intStats.randomize();
intStats.computeMean();
intStats.computeMedian();
intStats.computeMode();
intStats.displayStats();
System.out.println();
}
}
class ArrayStats
{
private int list[];
private int size;
private double mean;
private double median;
private int mode;
public ArrayStats(int s)//initializes class object
{
size = s;
list = new int[size];
}
public void randomize()
{
//This will provide same numbers every time... If you want to randomize this, you can
Random rand = new Random(555);
for (int k = 0; k < size; k++)
list[k] = rand.nextInt(11) + 10;
}
public void computeMean()
{
double accumulator=0;
for (int index=0;index<size;index++)
accumulator+= list[index];
mean = accumulator/size;
}
public void computeMedian()
{
Arrays.sort(list);
if((size%2!=0))
median = list[((size-1)/2)];
else if(size!=1&&size%2==0)
{
double a =(size)/2-0.5;
int a2 = (int)Math.ceil(a);
double b =(size)/2-0.5;
int b2 = (int)Math.floor(b);
median = (double)(list[a2]+list[b2])/2;
}
else if (size ==1)
median = list[0];
}
public void computeMode()
{
int popularity1 = 0;
int popularity2 = 0;
int array_item; //Array contains integer value. Make it String if array contains string value.
for(int i =0;i<list.length;i++){
array_item = list[i];
for(int j =0;j<list.length;j++){
if(array_item == list[j])
popularity1 ++;
}
if(popularity1 >= popularity2){
mode = array_item;
popularity2 = popularity1;
}
popularity1 = 0;
}}
public void displayStats()
{
System.out.println(Arrays.toString(list));
System.out.println();
System.out.println("Mean: " + mean);
System.out.println("Median: " + median);
System.out.println("Mode: " + mode);
System.out.println();
}
}
Arrays.sort(arr);
int max=0,mode=0,count=0;
for(int i=0;i<N;i=i+count) {
count = 1;
for(int j=i+1; j<N; j++) {
if(arr[i] == arr[j])
count++;
}
if(count>max) {
max=count;
mode = arr[i];
}
}