How to find i-th boolean from an array, with recursion? - java

Find i-th boolean from an array of boolean, for example: array is {true, true , false, false, true}, the method will output int that shows 3rd true value, that will be 4.
Some code i have already tried, it works but i need to use recursion, not a while function.
public static int check(int n, boolean[] b, boolean val){
int i = 0;
int count = 0;
while(i < b.length && count <= n){
if(b[i] == val) count++;
i++;
}
if(n == count){
return i;
}
else{
return -1;
}
}

You can do it like this :
int f(int n,boolean[] b,boolean val,int i)
{
if(i>=b.length)
return -1;
if(b[i]==val)
{
if(n==1)
return i;
else
return f(n-1,b,val,i+1);
}
return f(n,b,val,i+1);
}

public class Recursion {
private static boolean[] b = {true, true , false, false, true};
private static int i = 0;
private static int position = 0;
public static void check( int i, boolean[] b, boolean val ) {
if( i < b.length ) {
if( b[i] == val ) {
position = i;
}
i++;
check( i, b, val );
}
}
public static void main(String[] args) {
boolean myChoice = true;
check( Recursion.i, Recursion.b, myChoice );
System.out.println( "Last " + myChoice + " position computed is " + position );
}
}
Recursion is about a method calling itself. In the example above, the method checks if the 'counter' variable i is less than the length of the boolean array. Followed by a check of whether the current element of the array matches the selection. If so, the counter value is assigned to the position (last computed position). The counter is incremented, and the method calls itself.
The process continues until i is equal to the size of the boolean array. At that point, the method stop calling itself.

The actual function starts counting from 0, so I'm passing a position-1 inside. If i = 0, then it's quite obvious what we should return - the index of the first entry. If i is greater than 0, let's say it's 1, then we split the array into two parts: the part we already searched which contains the first entry, and the rest of an array. This can be done using subList(). Now we can use our function with i-1 on the rest of an array, which would find the index of the first entry in the second part of an array.
Also we have to add the size of what we cut out and that would be list.subList(0, list.indexOf(value) + 1).size() this is needed to remember the index in the original array.
public static void main(String[] args) {
List<Boolean> list = Arrays.asList(true, true, false, false, true, true, false, false); //8
int position = 4; //find index of fourth false
System.out.println(recursiveSearch(list, false, position - 1));
position = 2; //find index of second true
System.out.println(recursiveSearch(list, true, position - 1));
}
private static int recursiveSearch(List<Boolean> list, boolean value, int i) {
if(i == 0) {
return list.indexOf(value);
} else {
return list.subList(0, list.indexOf(value) + 1).size() + recursiveSearch(list.subList(list.indexOf(value) + 1, list.size()), value, i - 1);
}
}

Related

solution for jump game problem is not running properly

You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.
Return true if you can reach the last index, or false otherwise.
my code is running for some test cases but When I submit it gets failed, need help.
class Solution {
public boolean canJump(int[] nums) {
return helper(nums, 0);
}
public boolean helper(int[] nums, int currentPointer){
if(currentPointer == nums.length - 1) {
return true;
}
boolean ans = false;
for(int i = 1; i <= nums[currentPointer]; i++) {
ans = helper(nums, currentPointer + i);
}
if(ans) return true;
return false;
}
}

Return values from recursion

Could someone please help me with the recursion code below?
Given an input array and a target, I want to return a boolean true for any nonempty subset which sums up to the target value. I am confused about how to return the correct boolean value from recursion.
In my approach below, I am summing up all the possible combinations of a non-empty sub-set and want to return True to the calling function if any of the non-empty subsets equals the target value. The issue is, due to the multiple recursive call stacks, the correct/expected value for the boolean for a sub-set gets overwritten by the subsequent/remaining recursive call stacks. Is there a work-around for this issue? Or do I use brute force? where-in I store all the possible boolean values for each sub-set combination in a list and return true if atleast one value in the list is a boolean True?
public class RecursionPossibleToAchieveTargetSum {
public static void main(String[] args ) {
long[] arr = {4,8};
long k = 4;
boolean flag = false;
if (arr.length > 0 )
flag = recursionHelper(arr,0,new long[arr.length],0, k);
System.out.println(flag);
}
public static Boolean recursionHelper(long[] arr, int spos, long[] temp, int tempIndex, long target) {
if ( spos == arr.length ) {
return (recursiveAddition(temp, temp.length - 1) == target);
}
recursionHelper(arr, spos + 1, temp, tempIndex, target );
temp[tempIndex] = arr[spos];
return recursionHelper(arr, spos + 1, temp, tempIndex + 1, target);
}
public static long recursiveAddition(long[] arr, int spos) {
if ( spos == 0 ) {
return arr[spos];
} else {
return arr[spos] + recursiveAddition(arr, spos-1);
}
}
}
You can use a List<long[]> to save all the subsets that add up to the target. I also cleaned up the recursion a bit. You can check the size of this result list with "result.size() > 0" and print that boolean. You can also print each array of subsets to know which ones there are.
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
public class RecursionPossibleToAchieveTargetSum {
public static void main(String[] args ) {
long[] arr = {1,2,4,1,3,5};
long target = 8;
List<long[]> result = new ArrayList<long[]>();
if (arr.length > 0 ) {
result = recursionHelper(arr, target);
}
System.out.println(result.size() > 0);
for(long[] l : result) {
System.out.println(Arrays.toString(l));
}
}
public static List<long[]> recursionHelper(long[] arr, long target) {
List<long[]> result = new ArrayList<long[]>();
if (arr.length == 0) return result;
for(int j = arr.length; j > 0; --j) {
long nextsom = recursiveAddition(Arrays.copyOfRange(arr, 0, j));
if (nextsom == target) result.add(Arrays.copyOfRange(arr, 0, j));
}
result.addAll(recursionHelper(Arrays.copyOfRange(arr, 1, arr.length), target));
return result;
}
public static long recursiveAddition(long[] arr) {
if ( arr.length == 1 ) return arr[0];
return arr[0] + recursiveAddition(Arrays.copyOfRange(arr, 1, arr.length));
}
}
Example output with arr = {1,2,4,1,3,5} and target = 8:
true
[1, 2, 4, 1]
[4, 1, 3]
[3, 5]

Random Sort does not terminate

Assuming isAscSorted functions as expected (tested)
I am doing something silly here which is why random swap never sorts the array - because it is only ever doing 1 swap each time on different arrays?
My test case is
int[] values1 = new int[] { 50, 10, 20, 4, 5, 1, 5 };
Hints?
public static boolean isAscSorted (int[] arr){
for (int i=0; i<arr.length-1; i++){
if (arr[i]> arr[i+1]){
return false;
}
}
return true;
}
public static boolean swap(int[]a,int i,int j)
{
if (i == j){
return false;
}
int temp=a[i];
a[i]= a[j];
a[j]=temp;
return true;
}
static int randomSort(int[] values) {
//Ok Array is empty or null
if( values == null || values.length==0){
return 0;
}
boolean isSorted = false;
int steps = 0;
Random r = new Random();
int limit = values.length-1; //SOL: should be int limit = values.length;
while (!isAscSorted(values)){
//choose 2 random positions
int r1 = r.nextInt(limit);
int r2 = r.nextInt(limit);
//swap returns true if successful
boolean swapRes = swap(values, r1,r2);
//increment steps counter
if (swapRes)
steps++;
}
return steps;
}
The bug was with the use of Random.
I had indicated int limit = values.length-1;
This meant the last array position was never swapped and so the array could never be sorted (unless the 2nd and last numbers were identical and maximal for example).

Recursive search error

running into a silly error and I just don't see it. I've been looking at this for a while and don't see what I'm missing. I am recursively searching an array for a specific target number but once I get up to element [7] it begins returning -1. Thanks for taking a look fellas/ladies!
public static void main(String[] args)
{
int[] a = {1,25,2,6,4,3,23,30,32,14,11,8};
Arrays.sort(a);
int target = a[7];
int first = a[0];
int last = a.length;
for(int i=0;i<a.length;i++)
{
System.out.print(" "+a[i]);
}
System.out.println("\n"+binarySearch(target,first,last,a));
}
public static int binarySearch(int target,int first, int last, int[] a)
{
int result;
if(first>last)
return -1;
else
{
int mid = (first+last)/2;
if(target == mid)
result = mid;
else if(target<a[mid])
result = binarySearch(target,first,last-1,a);
else
result = binarySearch(target,mid+1,last,a);
}
return result;
}
In several places you fail to accurately distinguish between the value in an index of an array and the index itself.
This: a[i] gets the value at the ith element
This: i is simply an index, i
With that in mind, here is a fixed version of your code. See my comments in the code for some specific errors I fixed:
public static void main(String[] args)
{
int[] a = {1,25,2,6,4,3,23,30,32,14,11,8};
Arrays.sort(a);
int target = a[7];
//here you want the index of the first location to search, not the value in that index
//so you use 0 instead of a[0]
int first = 0;
//the last element index is length-1, not length, since arrays are 0-based
int last = a.length - 1;
for(int i=0;i<a.length;i++)
{
System.out.print(" "+a[i]);
}
System.out.println("\n"+binarySearch(target,first,last,a));
}
public static int binarySearch(int target,int first, int last, int[] a)
{
int result;
if(first>last)
return -1;
else
{
int mid = (first+last)/2;
//here you need to check if the target is equal to the value at the index mid
//before you were checking if the target was equal to the index, which was never true
if(target == a[mid])
//you want to return the value at the target, not the index of the target
//so use a[mid] not mid
result = a[mid];
else if(target<a[mid])
//here you want to search from first to mid-1
//before you were searching from first to last-1, which is not correct binary search
result = binarySearch(target,first,mid - 1,a);
else
result = binarySearch(target,mid + 1,last,a);
}
return result;
}

Finding a sub array in an array in Java

I am trying to write a program using two methods that determines if a sub array is located within an array. subArray() is supposed to receive two arrays and return the index of the start of the sub array within the array. If the sub array is not located in the array it returns -1. subArray() then calls subArrayAppearsAt() and passes in the two arrays and a location. subArrayAppearsAt() is supposed to return true if the sub array is located in the array starting at the location passed in, false otherwise.
Currently if I pass in array {1,2,3} and sub array {2,3}, it returns 2 as the starting position but it should return 1.
If I pass in array {1,2,3,4,5} and sub array {4}, it returns -1, but it should return 3.
Does anyone see why this might be happening?
public static int subArray(int [ ] array, int [ ] subArray )
{
boolean result=true;
int subArrayLength = subArray.length;
if (subArrayLength == 0) {
return -1;
}
int limit = array.length - subArrayLength;
int i;
for ( i = 0; i <= limit; i++)
result = subArrayAppearsAt(array, subArray, i );
if (result==true)
return i;
else
return -1;
}
public static boolean subArrayAppearsAt(int[] largeArray, int[] subArray, int i) {
{
if (subArray[0] == largeArray[i])
{
boolean subArrayFound = true;
for (int j = 1; j < subArray.length; j++)
{
if (subArray[j] != largeArray[i+j])
{
subArrayFound = false;
j=subArray.length;
}
/* Sub array found - return its index */
if (subArrayFound==true)
{
return true;
}
}
}
}
/* Return default value */
return false;
}
Look at this part
for ( i = 0; i <= limit; i++)
result = subArrayAppearsAt(array, subArray, i );
it sets result every time it goes through the loop. If you test if {4} is conatined in {1, 2, 3, 4, 5} it will set result to the return value of subArrayAppearsAt(array, subArray, 4); which will return false
So for that problem you could do something like
for ( i = 0; i <= limit; i++) {
result = subArrayAppearsAt(array, subArray, i );
if (result==true)
return i;
}
return -1;
The other problem is, that i will be incremented after it goes into the for-loop the last time, and then you return that value. That problem should be solved with my code solution too.
I didn't test my solution but it should work ;)
EDIT
Sorry that wasn't all correct. Your subArrayAppearsAt() returns true too early. Edit your subArrayAppearsAt() function to this and it should work
public static boolean subArrayAppearsAt(int[] largeArray, int[] subArray, int i)
{
if (subArray[0] == largeArray[i])
{
for (int j = 1; j < subArray.length; j++)
{
if (subArray[j] != largeArray[i+j])
{
return false;
}
}
return true;
}
return false;
}
The problem is that if you want to know the start position you should put the if that checks the result inside de loop
public static int subArray(int [ ] array, int [ ] subArray )
{
boolean result=true;
int subArrayLength = subArray.length;
if (subArrayLength == 0) {
return -1;
}
int limit = array.length - subArrayLength;
int i;
for ( i = 0; i <= limit; i++){
result = subArrayAppearsAt(array, subArray, i );
if (result==true)
return i;
}
return -1;
}
public static void main(String[] args) {
int[] first = {1,2,4,5,3,2,1,3,4,5,6,33,432,21,5};
int[] second = {2,1};
System.out.println(findpos(first, second));
}
private static int findpos(int[] a, int[] b){
for(int i=0; i<a.length; i++){
if(a[i]!=b[0]){
continue;
}
if(a.length - i < b.length) return -1;
int itemp = i;
boolean found = true;
for(int j=0; j<b.length; j++){
if(itemp < a.length && a[itemp]!=b[j]){
found = false;
}
itemp++;
}
if(found){
return i;
}
}
return -1;
}

Categories

Resources