/* * CSE 142 * Lecture - 5/14/2012 * Arrays For Tallying * Digit Frequency * * This program tests our implementation of mostFrequentDigits. * Our goal is to calculate which digit * occurs most frequently in several numbers. */ public class Frequency { public static final int BASE = 10; public static void main(String[] args) { int[] testDigits = {123121, 44222, 98799, 5678}; for (int i = 0; i < testDigits.length; i++) { int currentTest = testDigits[i]; System.out.println(currentTest + " -> " + mostFrequentDigit(currentTest)); } } // Returns the most frequently occuring digit within a number n. // If there is a tie, returns the lower digit. // Uses the count and max pattern we discussed. public static int mostFrequentDigit(int n) { // make an array with BASE elements (1 for each counter) int[] counts = new int[BASE]; // loop over input using mod by BASE trick while (n > 0) { int digit = n % BASE; // update correct counter (element 0 is count of 0s, elemnt 1 is count of 1s etc) counts[digit]++; n /= BASE; } // Traverse counts to find index of highest valued element. // Slightly different than other max problems we've solved. int highestIndex = 0; for (int i = 0; i < BASE; i++) { if (counts[i] > counts[highestIndex]) { highestIndex = i; } } return highestIndex; } // This is the implementation we looked at that doesn't use arrays. // It is super redundant, and doesn't handle bases other than 10 well. public static int terribleMostFrequentDigit(int n) { int count0 = 0; int count1 = 0; int count2 = 0; int count3 = 0; int count4 = 0; int count5 = 0; int count6 = 0; int count7 = 0; int count8 = 0; int count9 = 0; while (n > 0) { int digit = n % 10; if (digit == 0) { count0++; } else if (digit == 1) { count1++; } else if (digit == 2) { count2++; } else if (digit == 3) { count3++; } else if (digit == 4) { count4++; } else if (digit == 5) { count5++; } else if (digit == 6) { count6++; } else if (digit == 7) { count7++; } else if (digit == 8) { count8++; } else { // digit == 9 count9++; } n /= 10; } int best = 0; int bestCount = count0; if (count1 > bestCount) { bestCount = count1; best = 1; } if (count2 > bestCount) { bestCount = count2; best = 2; } if (count3 > bestCount) { bestCount = count3; best = 3; } if (count4 > bestCount) { bestCount = count4; best = 4; } if (count5 > bestCount) { bestCount = count5; best = 5; } if (count6 > bestCount) { bestCount = count6; best = 6; } if (count7 > bestCount) { bestCount = count7; best = 7; } if (count8 > bestCount) { bestCount = count8; best = 8; } if (count9 > bestCount) { bestCount = count9; best = 9; } return best; } }