Skip to content

Instantly share code, notes, and snippets.

@yawboakye
Last active December 23, 2015 15:29
Show Gist options
  • Save yawboakye/6655789 to your computer and use it in GitHub Desktop.
Save yawboakye/6655789 to your computer and use it in GitHub Desktop.
I tried to find the mode of elements in an array without using any of Java Array's methods
import java.util.Arrays;
public class Mode {
private ModeOccurrence<Object, Integer> modeOccurrence;
Mode() {
this.modeOccurrence = new ModeOccurrence<>(null, -1);
}
public static void main(String[] args) {
if (args.length == 0) {
System.err.println("Man, warrisdat?");
System.exit(1);
}
if (args.length == 1) {
System.out.println(args[0]);
System.exit(0);
}
Mode modeFinder = new Mode();
ModeOccurrence<Object, Integer> modeAndCount = modeFinder.findMode(args);
System.out.println(modeAndCount);
}
public ModeOccurrence<Object, Integer> findMode(Object[] array) {
Object[] copyOfArguments = duplicateArray(array);
Arrays.sort(copyOfArguments);
Object mode = null;
int modeCount = 0;
Object previousElement = copyOfArguments[0];
int currentElementCount = 0;
for (int i = 0; i < copyOfArguments.length; i++) {
Object currentElement = copyOfArguments[i];
// Check whether current element is same as previous
if (currentElement.equals(previousElement)) {
// if previous and current element are the same
// increment count for number of appearances of current
currentElementCount++;
} else {
// otherwise change cached previous to current element
if (currentElementCount > modeCount) {
// if appearances of current element is highest so far
// save current element as mode and currentElementCount as mode count
mode = previousElement;
modeCount = currentElementCount;
}
previousElement = currentElement;
// reset current element count
currentElementCount = 1;
}
if ( i == copyOfArguments.length - 1 ) {
if (currentElementCount > modeCount) {
mode = currentElement;
modeCount = currentElementCount;
}
}
}
this.modeOccurrence.mode = mode;
this.modeOccurrence.modeCount = modeCount;
return modeOccurrence;
}
public static Object[] duplicateArray(Object[] original) {
Object[] copy = new Object[original.length];
System.arraycopy(original, 0, copy, 0, original.length);
return copy;
}
class ModeOccurrence<E, Integer> {
public final E mode;
public final int modeCount;
ModeOccurrence(E mode, int modeCount) {
this.mode = mode;
this.modeCount = modeCount;
}
public String toString() {
return String.format("%s(%d)", mode.toString(), this.modeCount);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment