|
| 1 | +package easy; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +/** |
| 7 | + * Have the function MeanMode(arr) take the array of numbers stored in arr |
| 8 | + * and return 1 if the mode equals the mean, 0 if they don't equal each other |
| 9 | + * (i.e. [5, 3, 3, 3, 1] should return 1 because the mode (3) equals the mean (3)). |
| 10 | + * The array will not be empty, will only contain positive integers, |
| 11 | + * and will not contain more than one mode. |
| 12 | + */ |
| 13 | +public class MeanMode { |
| 14 | + |
| 15 | + /** |
| 16 | + * Mean Mode function. |
| 17 | + * |
| 18 | + * @param arr input array. |
| 19 | + * @return 1 if the mode equals the mean, 0 if they don't equal each other |
| 20 | + */ |
| 21 | + private static String meanMode(int[] arr) { |
| 22 | + int sum = 0; |
| 23 | + int modeKey = 0; |
| 24 | + int modeVal = 0; |
| 25 | + |
| 26 | + Map<Integer, Integer> modeMap = new HashMap<>(); |
| 27 | + for (int item : arr) { |
| 28 | + modeMap.put(item, 0); |
| 29 | + } |
| 30 | + |
| 31 | + for (int value : arr) { |
| 32 | + sum += value; |
| 33 | + int val = modeMap.get(value); |
| 34 | + if (val > 0) { |
| 35 | + modeMap.put(value, val + 1); |
| 36 | + } else { |
| 37 | + modeMap.put(value, 1); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + for (Map.Entry<Integer, Integer> item : modeMap.entrySet()) { |
| 42 | + int itemKey = item.getKey(); |
| 43 | + int itemVal = item.getValue(); |
| 44 | + if (itemVal > modeVal) { |
| 45 | + modeVal = itemVal; |
| 46 | + modeKey = itemKey; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return modeKey == (sum / arr.length) ? "1" : "0"; |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Entry point. |
| 55 | + * |
| 56 | + * @param args command line arguments |
| 57 | + */ |
| 58 | + public static void main(String[] args) { |
| 59 | + var result1 = meanMode(new int[]{5, 3, 3, 3, 1}); |
| 60 | + System.out.println(result1); |
| 61 | + var result2 = meanMode(new int[]{64, 64, 64, 64, 64, 64, 64, 64, 1024}); |
| 62 | + System.out.println(result2); |
| 63 | + } |
| 64 | + |
| 65 | +} |
0 commit comments