Recursion - if there is continuity of numbers in java -


i have exercise error , love on error , how fix exercise.

write recursive function receives set of numbers , number between 9-1. function returns true if there continuity of numbers 1 number, otherwise returns false.

it brings me true, there no error.

examples:

for array 3,1,2,3,4,6,3 , number 4 returned true

for array 3,1,2,1,2,3,5 , number 4 returned false

the code:

public static boolean continuityofnumbers(int[] arr, int n) {     int counter = 0;     int index = arr.length - 1;      if (n == 0)             return true;      if (arr[index] - 1 == arr[index - 1])         counter += 1;      index--;      return continuityofnumbers(arr, n - 1); } 

here o(n) runtime , storage complexity solution. makes boolean continuity array , checks , end of recursion.

don't copy-paste it, make sure read comments in code see logic is, , make sure understand it.

it additionally pre-validation checks make sure n contained , reachable in array before doing recursion.

private static boolean continuityofnumbers(int[] arr, int n) {     // max sure can reach n     if (n >= arr.length) return false;      // make sure n in array     boolean findn = false;     // find max value in array     int max = integer.min_value;     (int x : arr) {         if (x == n) findn = true;         if (max < x) max = x;     }     // if n not found or still cant reach n, return false     if (!findn || n > max) return false;      // build continuity array of false     boolean[] contarr = new boolean[n];      // start recursion     return continuityofnumbers(arr, n, contarr, 0); }  private static boolean continuityofnumbers(int[] arr, int n, boolean[] contarr, int index) {     // base case - reached end of array     if (index >= arr.length) {         // check values n true         (int = 0; < n; i++) {             if (!contarr[i]) return false;         }         // here, know values continuous         return true;     }      // set index of continuity array non-zero value     int val = arr[index];     if (val <= n && !contarr[val-1]){         contarr[val-1] = true;     }      // recurse next index     return continuityofnumbers(arr, n, contarr, index+1); } 

for function 3, 1, 2, 3, 4, 6, 3 n = 4, here sample debug run 0 being false , true being 1.

start:  [0, 0, 0, 0] set 3:  [0, 0, 1, 0] set 1:  [1, 0, 1, 0] set 2:  [1, 1, 1, 0] set 4:  [1, 1, 1, 1] true 

and same numbers n = 6 (should return false since 5 doesn't not exist).

start:  [0, 0, 0, 0, 0, 0] set 3:  [0, 0, 1, 0, 0, 0] set 1:  [1, 0, 1, 0, 0, 0] set 2:  [1, 1, 1, 0, 0, 0] set 4:  [1, 1, 1, 1, 0, 0] set 6:  [1, 1, 1, 1, 0, 1] false 

Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -