puzzle:
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
And my code here:
public class Solution {
public static int searchInsert(int[] nums, int target) {
return searchInsert(nums, target, 0, nums.length-1);
}
private static int searchInsert(int[] nums, int target, int start, int end) {
if(start <= end) {
return target <= nums[start] ? start : (start+1);
}
int m = (start + end) / 2;
if(nums[m] == target) {
return m;
} else if(nums[m] < target) {
return searchInsert(nums, target, m+1, end);
} else {
return searchInsert(nums, target, start, m-1);
}
}
public static void main(String[] args) {
int[] nums = {1, 3};
System.out.print(searchInsert(nums, 4);
}
}
The result turns out like this:
Input:
[1,3]
4
Output:
1
Expected:
2
I've simulate the process of this input over and over again on paper, but just cannot figure out how my code could output 2.
Please help me with this, thx in advance.
The condition:
start <= end
is incorrect. The condition is true immediately for a non-zero length array, because start == 0 and end == <something which is at least 0>, so it will return either start or start+1 straight away - in your case, start+1.
Related
Problem:
Find the maximum length of contagious subarray with repeated elements.
eg:
[1 2 2 2 3 3 5 1 8] - answer is 3 since 2 repeated 3 times is the max repeated times.
[1 2] - answer is 1
[1 2 2 3 3] - answer is 2
But the recursive function should only have list as the argument. int findMaxContagiousRepeatedLength(List<Integer> list)
What I've tried:
class Answer
{
public static int findMaxContagiousRepeatedLength(List<Integer> nums, int currentCount, int latestNumber)
{
if (nums.isEmpty())
return 0;
if (nums.get(0) == latestNumber) {
return Math.max(currentCount+1, findMaxContagiousRepeatedLength(nums.subList(1, nums.size()), currentCount+1, nums.get(0)));
} else {
return findMaxContagiousRepeatedLength(nums.subList(1, nums.size()), 1, nums.get(0));
}
}
public static void main(String[] args)
{
Integer[] nums = { 1,2,1,1,1,1,1,2,3,2,3,1,2,2};
System.out.println("Max length: " +
findMaxContagiousRepeatedLength(Arrays.asList(nums), 0, nums.length == 0 ? -1 : nums[0]));
}
}
The above does work, but doesn't meet the requirement of argument restriction.
Please help me figure out if it's possible to have a solution where recursive function only have list as the argument.
Best solution
Use your Function
public static int findMaxContagiousRepeatedLength(List<Integer> nums, int currentCount, int latestNumber)
{
if (nums.isEmpty())
return 0;
if (nums.get(0) == latestNumber) {
return Math.max(currentCount+1, findMaxContagiousRepeatedLength(nums.subList(1, nums.size()), currentCount+1, nums.get(0)));
} else {
return findMaxContagiousRepeatedLength(nums.subList(1, nums.size()), 1, nums.get(0));
}
}
and make a second Function which calls your function with default parameters
public static int findMaxContagiousRepeatedLength(List<Integer> nums)
{
return findMaxContagiousRepeatedLength(Arrays.asList(nums), 0, nums.length == 0 ? -1 : nums[0]);
}
Now you can call the second function which calls the first function with default parameters!
First, this problem is best solved by just going through the list.
But if you must use recursion with List<Integer> as the only parameter you may use the below:
public static int findMaxContiguousRepeatedLength(List<Integer> nums) {
if (nums.isEmpty()) {
return 0;
}
Iterator<Integer> it = nums.iterator();
Integer start = it.next();
int len = 1, pos = 1;
while (it.hasNext()) {
Integer curr = it.next();
if (curr == start) {
pos++;
len++;
} else {
break;
}
}
return Math.max(len, findMaxContiguousRepeatedLength(nums.subList(pos,nums.size())));
}
If you're allowed to (temporarily) modify the list, the below approach would also work:
public static int findMaxContiguousRepeatedLength(List<Integer> nums) {
if (nums.isEmpty()) {
return 0;
}
// carve out repeated chunk from back
Integer back = nums.remove(nums.size() - 1);
int repeats = 1;
while(!nums.isEmpty() && nums.get(nums.size() - 1) == back) {
nums.remove(nums.size() - 1);
repeats++;
}
int res = Math.max(repeats, findMaxContiguousRepeatedLength(List<Integer> nums));
while(repeats) { // restore
repeats--;
nums.add(back);
}
return res;
}
So the exercise is:
Using recursion only (no loops)
Find if there is sub ground of numbers that are equal to the given number in an array and follow the rule.
Let's say I have this array, I give the function a number for sum and it must adhere to this rule:
you cannot repeat the same number, and you can't sum 3 numbers in a row (can't do i+1 and i+2)
int[] a = {5,4,2,1,3};
So in this case:
num 8 = true (4+3+1) ( 5+3)
num 11 = false (4+5+2 are 3 but are three in a row) (5+2+1+3 also three in a row)
My attempt is:
public static boolean sumRule(int[] a , int num){
if (num == 0){
return true;
} else {
return sumRule(a,num,0,a.length);
}
}
private static boolean sumRule(int[] a, int num, int low,int high){
if(low >= high || low < 0){
return false;
}
if (a[low] == -1){
return false;
}
if(a[low] == num || num-a[low] == 0 ){
return true;
}
int temp = a[low];
a[low] = -1;
return sumRule(a,num,low,high) || sumRule(a,num-temp,low+3,high) || sumRule(a,num-temp,low+1,high) ;
}
But when I send 11 to this, it still returns true, anyone has an idea what am i missing here?
Thanks,
I have the full code answer below, and here's the explanation:
Essentially you need to break this problem down to a recurrence. What that means is, you look at the choice at each step (i.e. whether to use a number or not in the sum) and recursively calculate both options.
The base case:
If num == 0 then we know it's true. But if num != 0 and the array has length 0, then we know it's false
Recursive case:
We check if the first number in the array is less than or equal to num. If not, then we can't use it. So we do a recursive call with all the same parameters except the array is now the original array minus the first number
If we CAN use the number (i.e. a[0] <= num) then the true answer might use this or it may not use it. We make a recursive call for each case, and return true if either of the recursive calls return true.
The consecutive number rule:
This is easy to enforce. We add a parameter called 'left' which tells us the number of elements we can consecutively take from the beginning of the array. To start with, left is 2 because at most we can take 2 consecutive numbers. Then in the cases where we DO use the first number in the array in our sum, we decrement left. If we don't use the first number in the array, we reset left to 2. In the cases where left becomes 0, we have no choice but to skip the current number at the top of the array.
class Main {
public static void main(String[] args) {
int[] a = new int[] {5,4,2,1,3};
System.out.println(sumRule(a, 8));
System.out.println(sumRule(a, 11));
}
public static boolean sumRule(int[] a , int num){
if (num == 0){
return true;
} else {
return sumRule(a,num,2);
}
}
private static boolean sumRule(int[] a, int num, int left){
if (num == 0) {
return true;
}
if (a.length == 0) {
return false;
}
int[] a_new = new int[a.length-1];
for (int i = 1; i < a.length; i++) a_new[i-1] = a[i];
if (left == 0) {
return sumRule(a_new, num, 2);
}
boolean using_a0 = false;
if (a[0] <= num) {
using_a0 = sumRule(a_new, num-a[0], left-1);
}
boolean not_using_a0 = sumRule(a_new, num, 2);
return (not_using_a0 || using_a0);
}
}
Edit - A variation on the code above without copying the array:
class Main {
public static void main(String[] args) {
int[] a = new int[] {5,4,2,1,3};
System.out.println(sumRule(a, 8));
System.out.println(sumRule(a, 11));
}
public static boolean sumRule(int[] a , int num){
if (num == 0){
return true;
} else {
return sumRuleNoLoop(a,num,2,0);
}
}
private static boolean sumRuleNoLoop(int[] a, int num, int left, int startIdx){
if (num == 0) {
return true;
}
if (startIdx >= a.length) {
return false;
}
if (left == 0) {
return sumRuleNoLoop(a, num, 2, startIdx+1);
}
boolean using_a0 = false;
if (a[startIdx] <= num) {
using_a0 = sumRuleNoLoop(a, num-a[startIdx], left-1, startIdx+1);
}
boolean not_using_a0 = sumRuleNoLoop(a, num, 2, startIdx+1);
return (not_using_a0 || using_a0);
}
}
First thing you can add is a check to see not 3 numbers in a row being added. Also replacing a number in the array with -1 would have unintended side effects within recursive calls. Below is something I have. You can ignore the index param I have used to see the values used.
Explanation:
The recursive sumRule method divides the problem into two parts:
First part takes the value of current index and adds with the sum of values starting from next index.
Second part assumes, current value can’t be taken for the sum. It only checks if there is a sum within the subset starting from next value of the array.
In the method, lastIndex is keeping track of the index of last value picked up for the sum. So, in the first call the value is 0, 1 in second and so on.
(start - lastIndex <= 1 ? consecutive + 1 : 1) is to check whether value of consecutive should be increased or not. consecutive = 1 means, current value is added to the sum.
public static boolean sumRule(int[] a, int num) {
if (num == 0) {
return true;
} else {
return sumRule(a, num, 0, 0, 0, 0, "");
}
}
public static boolean sumRule(final int[] a, int num, int sum, int start, int consecutive, int lastIndex,
String index) {
if (consecutive == 3) {
return false;
}
if (sum == num) {
System.out.println(index);
return true;
}
if (start >= a.length) {
return false;
}
return sumRule(a, num, sum + a[start], start + 1, (start - lastIndex <= 1 ? consecutive + 1 : 1), start,
index + ", " + start) || sumRule(a, num, sum, start + 1, consecutive, lastIndex, index);
}
Here is my implementation. It contains comments explaining what the different parts do.
public class RecurSum {
/**
* Determines whether 'sum' equals 'target'.
*
* #param arr - its elements are summed
* #param sum - sum of some elements in 'arr'
* #param target - required value of 'sum'
* #param index - index in 'arr'
* #param consecutive - number of consecutive indexes summed to ensure don't exceed 3
* #param start - starting element in 'arr' which is used for back-tracking
*
* #return "true" if 'sum' equals 'target'
*/
private static boolean sumRule(int[] arr, int sum, int target, int index, int consecutive, int start) {
if (sum == target) {
return true;
}
else {
if (index >= arr.length) {
// if we have reached last element in 'arr' then back-track and start again
if (start < arr.length) {
return sumRule(arr, 0, target, start + 1, 0, start + 1);
}
// we have reached last element in 'arr' and cannot back-track
return false;
}
else {
consecutive++;
if (consecutive == 3) {
// skip 3rd consecutive element (because of the rule)
consecutive = 0;
return sumRule(arr, sum, target, index + 2, consecutive, start);
}
else {
if (sum + arr[index] > target) {
// recursive call but don't add current element of 'arr'
return sumRule(arr, sum, target, index + 1, 0, start);
}
// recursive call: add current element of 'arr' to 'sum' and proceed to next element
return sumRule(arr, sum + arr[index], target, index + 1, consecutive, start);
}
}
}
}
public static void main(String[] args) {
int[] arr = new int[]{5, 4, 2, 1, 3};
// initial call to recursive method with target = 11 (eleven)
System.out.println(sumRule(arr, 0, 11, 0, 0, 0));
// initial call to recursive method with target = 8
System.out.println(sumRule(arr, 0, 8, 0, 0, 0));
}
}
I am having a problem with converting a while loop to a recursion ... the loop seems to work fine however I tried several times to turn it to recursion and what the method returns is the last (return c;) as 0 ... I mean how can you actually turn a while loop into a recursion? the program should count the numbers below 2 in the array
thats the main
public static void main(String[] args) {
double[] gpa = new double[]{2.5, 1.3, 1.3, 3.3, 1.2, 3.2, 4, 2.3, 3.1, 1.2};
int start = 0;
countGPA(gpa,start);
System.out.println(countGPA(gpa, start));
}
and thats the method
public static int countGPA(double[] gpas, int start) {
int L = gpas.length;
int c = 0;
int countGPA = c;
while (start < 10) {
if (start > 0 && start != L) {
if (gpas[start] < 2.0 && gpas[start] > 0) {
c++;
}
} else if (start == L) {
return 0;
} else if (start < 0 && start > L) {
return -1;
}
start++;
}
return c;
}
This looks like a simple recursion:
public int GPA(double[] gpas, int index){
if(index >= gpas.length) return 0;
if(0 < gpas[index] && gpas[index] < 2) return 1 + GPA(gpas, index + 1);
else return GPA(gpas, index + 1);
}
Just call it GPA(gpa, 1).
There is a lot of unnecessary comparisons in your method. Look at your uses of 10, L and start.
For example, suppose start = 0. No one of your ifs will enter. Better to start with 1. Look:
if (start > 0 && start != L) //start is 0 so this won't enter
else if (start == L) //start is 0 so this won't enter
else if (start < 0 && start > L) //start is 0 so this won't enter
There are three most important things about a recursive function/method:
The terminating condition.
The value with which the method/function is called recursively.
Where (before/after the recursive call) to process the parameter(s).
Do it as follows:
public class Main {
public static void main(String[] args) {
double[] gpa = new double[] { 2.5, 1.3, 1.3, 3.3, 1.2, 3.2, 4, 2.3, 3.1, 1.2 };
int start = 0;
System.out.println(countGPA(gpa, start));
}
public static int countGPA(double[] gpas, int start) {
return countGPA(gpas, start, 0);
}
public static int countGPA(double[] gpas, int start, int count) {
if (start >= gpas.length) {// Terminating condition
return count;
}
if (gpas[start] < 2.0 && gpas[start] > 0) {
return countGPA(gpas, ++start, ++count);// The recursive call
} else {
return countGPA(gpas, ++start, count);// The recursive call
}
}
}
Output:
4
Two important things to note when creating recursive methods.
You must include a base case, that when true stops the recursive calls and returns the values. If you don't have a base case, you'll run into a StackOverFlow exception.
In your scenario the recursion will stop when the index value is equal to the length of the array.
The method must call itself from within.
Anything that can be iterated over can also be a candidate for recursion.
Info on recursion: https://www.javatpoint.com/recursion-in-java
public int numbersBelowTwo(double[] gpas, int index){
//Base case, when this statement equates to true
//the recursions stops and returns the values.
if (index == gpas.length) return 0;
return gpas[index] < 2 ? 1 + numbersBelowTwo(gpas, ++ index) : numbersBelowTwo(gpas, ++index);
}
I need a little help with finding an integer in an array. The array must be non sorted, and the algorithm must be done recursively. My peers and I have came up with the solution to cut the array in half, check if the middle number is the value we are looking for, if not, it cuts itself in half and keeps repeating itself, until it moves on to other parts of the array and eventually stops. So far, I have been experimenting with my code, here it is. I would like to know where this is going wrong, and how can I improve it or make it fully work? Thank you
import java.util.*;
public class BinarySearch {
public static int search(int[] a, int low, int high, int value, int count)
{
int mid = (low + high) / 2;
if(a[mid] == value)
{
return mid;
}
if(a[mid] < value)
{
count = a[mid];
if(a[count] != value)
{
count--;
return search(a, mid + 1, high, value, count);
}
}
else
{
count = a[mid];
if(a[count] != value){
count++;
return search(a, low, mid - 1, value, count);
}
}
return low;
}
public static void main(String[] args)
{
BinarySearch BS = new BinarySearch();
int[] a = {5, 7, 1, 2, 4, 12, 9, 8, 89};
int value = 9;
int result = BS.search(a, 0, 0, value, 0);
if(result == -1)
{
System.out.print("the Value is not in the array!" );
}
else
{
System.out.print("the Value is in the array!" );
}
}
}
I am trying to write a program that will take an ArrayList of sorted integers, and there will be a binary search method where you specify the range and the values that you want to be returned from the ArrayList.
import java.util.ArrayList;
public class ArraySearch {
ArrayList<Integer> myArrayList = new ArrayList<Integer>();
static ArrayList<Integer> range = new ArrayList<Integer>();
public static ArrayList<Integer> binarySearch(ArrayList<Integer> arrayList, int min, int max, int first, int last)
throws NotFoundException {
if(first > last) {
throw new NotFoundException("Elements not found.");
}
else {
int middle = (first + last) /2;
int mid_number = arrayList.get(middle);
if(mid_number >= min && mid_number <= max)
{
range.add(middle);
}
if(mid_number <= min) {
if(mid_number == min) {
range.add(arrayList.get(middle));
return binarySearch(arrayList, min, max, first, middle-1);
}
return binarySearch(arrayList, min, max, first, middle-1);
}
else {
if(mid_number == max) {
range.add(arrayList.get(middle));
return binarySearch(arrayList, min, max, middle+1,last);
}
return binarySearch(arrayList, min, max, middle+1,last);
}
}
}
public static void main (String [] args) throws NotFoundException {
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(0);
a.add(1);
a.add(2);
a.add(3);
a.add(6);
a.add(7);
a.add(7);
a.add(10);
a.add(10);
a.add(10);
binarySearch(a, 3, 7, 0, 9);
}
}
Could I please get some help?
I have no idea what the base case condition should be that should return the ArrayList range. And I think I might have got the logic in the binary search method wrong.
First , find the lower index range of the element. then , find the upper index range of the element .
To find lower index range, when you find the element, instead of breaking out of the loop, like we do so in normal search. put the value in index and make the mid one less than the current index you are checking. This will make the loop go again to find the lower index and not stop at the first index.
Similarly for the upper index , update start to the current index we are checking + 1.
Have a look at the code.
public ArrayList<Integer> searchRange(ArrayList<Integer> a, int b) {
int first=lowerIndex(a,b);
int last=upperIndex(a,b);
ArrayList<Integer> result= new ArrayList<Integer>();
result.add(first);
result.add(last);
return result;
}
public int upperIndex(ArrayList<Integer> a, int b) {
int index=-1; //will return -1 if element not found.
int start=0;
int end=a.size()-1;
while(start<=end){
int mid=(start+end)/2;
if(a.get(mid)==b){
index=mid; //Update Index, which is the upper index here.
start=mid+1; // This is the main step.
}
else if(a.get(mid)>b){
end=mid-1;
}
else{
start=mid+1;
}
}
return index;
}
public int lowerIndex(ArrayList<Integer> a, int b) {
int index=-1; // will return -1 if element not found
int start=0;
int end=a.size()-1;
while(start<=end){
int mid=(start+end)/2;
if(a.get(mid)==b){
index=mid; //Update Index, which is the lower index here.
end=mid-1; // This is the main step .
}
else if(a.get(mid)>b){
end=mid-1;
}
else{
start=mid+1;
}
}
return index;
}