Basically, what you can do is not all the permutations that you create for each value in the array. For example, if we have 2, we know that the hour should be 2 for our ten places, but our spots for the hour can only be 3 at that moment. If we have 1, then we know that our one place for an hour can be 9. We know that our ten minute spot is 5 and our maximum minute point is 9. createTime shows these conditions. The findMaxSpecific function returns -1 if it cannot find a valid number in the given array. So we know that time is invalid if we ever get the array returned by createTime with -1 in it. See sample output.
public static int[] createTime(int[] numbers) { int[] time = new int[4]; time[0] = findMaxSpecific(numbers, 2); time[1] = time[0] == 2 ? findMaxSpecific(numbers, 3) : findMaxSpecific(numbers, 9); time[2] = findMaxSpecific(numbers, 5); time[3] = findMaxSpecific(numbers, 9); return time; } public static int findMaxSpecific(int[] arr, int valToFind) { if(arr.length != 4) return -1; int numToFind = -1; int indexToRemove = -1; for(int i = 0; i < arr.length; i++) { if(arr[i] <= valToFind) { if(arr[i] > numToFind) { numToFind = arr[i]; indexToRemove = i; } } } if(indexToRemove == -1) return -1; arr[indexToRemove] = -1; return numToFind; }
At the end of all this, if any value is returned as -1, we know that we have an invalid time given to us
Example
int[] time = new int[4]; int[] numbers = {1,2,3,4}; time = createTime(numbers); System.out.println(time[0] + "" + time[1] + ":" + time[2] + "" + time[3]); int[] numbers2 = {0,9,7,1}; time = new int[4]; time = createTime(numbers2); System.out.println(time[0] + "" + time[1] + ":" + time[2] + "" + time[3]); int[] numbers3 = {9,9,9,9}; time = new int[4]; time = createTime(numbers3); System.out.println(time[0] + "" + time[1] + ":" + time[2] + "" + time[3]);
Output
23:41 19:07 -19:-19
source share