Given an array of ints, compute recursively if the array contains a 6. We'll use the convention of considering only the part of the array that begins at the given index. In this way, a recursive call can pass index+1 to move down the array. The initial call will pass in index as 0.
array6([1, 6, 4], 0) → true
array6([1, 4], 0) → false
array6([6], 0) → true
Java :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public static boolean array6(int[] nums, int index) { //Stop condition if(nums.length == 0) return false; if(nums.length == 1) { if(nums[0]== 6) return true; else return false; } //Main process if(nums[index] == 6) return true; int[] temp = Arrays.copyOfRange(nums, index+1, nums.length); return array6(temp,index); } |
Test Result:
C# :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public static Boolean array6(int[] nums, int index) { //stop condition if (nums.Length == 0) return false; if (nums.Length == 1) { if (nums[0] == 6) return true; else return false; } if(nums[index] == 6) return true; //Main recursive process int[] temp = new int[nums.Length-index-1]; System.Array.Copy(nums,index+1,temp,0,temp.Length); return array6(temp, index); } |
Test Result:
No comments:
Post a Comment