|
| 1 | +package com.google.challenges; |
| 2 | + |
| 3 | +/** |
| 4 | + * A brute force solution to the challenge, but considering there are only 100 integers |
| 5 | + * in the array, it works. |
| 6 | + */ |
| 7 | +public class Answer { |
| 8 | + |
| 9 | + /** |
| 10 | + * Actual method for the challenge. |
| 11 | + * |
| 12 | + * Will take in the array of integers data, and remove all instances of an element |
| 13 | + * that appears more than n times. |
| 14 | + * |
| 15 | + * @param data: the array of integers to check |
| 16 | + * @param n: the maximum number of times that an element can appear in the array |
| 17 | + */ |
| 18 | + public static int[] answer(int[] data, int n) { |
| 19 | + int i = 0; |
| 20 | + |
| 21 | + //go through entire array (it will change size) |
| 22 | + while (i < data.length) { |
| 23 | + //element appears in array than n times |
| 24 | + if (count(data, data[i]) > n ) { |
| 25 | + //remove all instances of value in array |
| 26 | + data = removeValue(data, data[i]); |
| 27 | + } else { |
| 28 | + //it appears less than n times, so move to check next element |
| 29 | + i++; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + return data; //return the newly trimmed array |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Will count the number of times an element (the number) appears in the array. |
| 38 | + * |
| 39 | + * @param data: the array of integers |
| 40 | + * @param number: the number to check how many times it appears in the array |
| 41 | + */ |
| 42 | + public static int count(int[] data, int number) { |
| 43 | + int count = 0; //track number of times it appears |
| 44 | + for (int i = 0; i < data.length; i++) { |
| 45 | + if (data[i] == number) { |
| 46 | + count++; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return count; |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Will return a new array with all instances of the given number removed. |
| 55 | + * |
| 56 | + * @param data: the array of integers of which to remove the number |
| 57 | + * @param number: the number to be removed from the array. |
| 58 | + */ |
| 59 | + public static int[] removeValue(int[] data, int number) { |
| 60 | + //integer holding length of the old array - the number of times |
| 61 | + int newLength = data.length-count(data,number); |
| 62 | + int[] newValues = new int[newLength]; //new array with the length |
| 63 | + int track = 0; //index tracker for the new array |
| 64 | + |
| 65 | + //iterate through the old array |
| 66 | + for (int i = 0; i < data.length; i++) { |
| 67 | + //if the current element is not the number |
| 68 | + if (data[i] != number) { |
| 69 | + newValues[track] = data[i]; //add it to the new array |
| 70 | + track++; //increase the index tracker for the new array |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + return newValues; //return the new array |
| 75 | + } |
| 76 | +} |
0 commit comments