Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- public class Mode {
- // find 1 or more modes from an array
- // the mode is the most repeated successive number
- // there can be more than one mode
- /**
- * Program: Modes.java
- * Purpose: Yahoo! Answers
- * Creator: Chris Clarke
- * Created: 30.11.2013
- */
- public static void main(String[] args) {
- // test data
- int[] num = {2,2,3,4,7,7,7,8,8,8}; // removed an 8 - for test purposes
- ArrayList<Integer> numberList = new ArrayList<>(); // number
- ArrayList<Integer> frequencyList = new ArrayList<>(); // frequency
- ArrayList<Integer> modeList = new ArrayList<>(); // 1 or more max repeats
- int repeats = 1; // starts with 1 of current number
- int max = 1; // max is 1 to begin with
- for (int x=0; x < num.length; x++) {
- if (x < num.length-1) {
- if (num[x] == num[x+1]) { // a repeated number
- if (++repeats > max) {
- max = repeats;
- } // end if repeats
- } else {
- if (!numberList.contains(num[x])) {
- numberList.add(num[x]); // add the number to list
- frequencyList.add(repeats); // add frequency to list
- } // end if
- repeats = 1; // new number, not repeat
- } // end if num
- } else {
- if (!numberList.contains(num[x])) {
- numberList.add(num[x]); // add the number to list
- frequencyList.add(repeats); // add frequency to list
- } // end if
- repeats = 1;
- } // end if x
- } // end for
- // find all numbers whose frequency = max
- for (int i=0; i<frequencyList.size(); i++) {
- if (frequencyList.get(i) == max) {
- modeList.add(numberList.get(i));
- } // end if
- } // end for
- // output result(s)
- System.out.print("The numbers are ");
- for (int i: num) {
- System.out.printf("%d ", i);
- } // end for
- System.out.println("\nnumberList = "+numberList);
- System.out.println("frequencyList = "+frequencyList);
- System.out.println("Mode(s) = "+modeList);
- } // end main()
- } // end class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement