solution for jump game problem is not running properly - java

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;
}
}

Related

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

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);
}
}

Detecting duplicates in an array

Pretty new to this and I've exhausted numerous attempts to figure out why this isn't working but can't get it.
private int indexOf(int searchingNum)
{
int x = searchingNum;
for (int i = 0; i<numberArray.length; i++){
if (numberArray[i]==x)
index = i;
else
index = -1;
}
return index;
}
public boolean addNumber(int numberToAdd)
{
int x = numberToAdd;
if (indexOf(x)!=-1)
return false;
if (count<numberArray.length&&indexOf(x)==-1){
count++;
numberArray[count-1] = x;
return true;
}
if (count>=numberArray.length&&indexOf(x)==-1){
count++;
newArray = Arrays.copyOf(numberArray, 2* numberArray.length);
numberArray = newArray;
numberArray[count-1] = x;
}
return true;
}
The method should't allow for duplicates but does. Any pointers in the right direction would be much appreciated.
Thank you.
Your indexOf is incorrect: since you continue the loop after finding a match, your code returns -1 unless the last item in the array happens to match.
To fix this problem, return i from inside the loop:
for (int i = 0 ; i < numberArray.length ; i++) {
if (numberArray[i]==x)
return i;
}
// If we are here, we did not find anything; return -1
return -1;
Here's a precise version of your code :
private boolean contains(int searchingNum)
{
for (int i = 0; i<numberArray.length; i++){
if (numberArray[i]==x)
return true;
}
return false;
}
public boolean addNumber(int numberToAdd)
{
int x = numberToAdd;
if (contains(x))
return false;
if (count<numberArray.length){
count++;
numberArray[count-1] = x;
}
else{
count++;
int []newArray = Arrays.copyOf(numberArray, 2* numberArray.length);
numberArray = newArray;
numberArray[count-1] = x;
}
return true;
}
Try this. Meanwhile, it can only gurantee you the uniqueness of the elements if the array wasn't previously initialised, i.e. all elements are added in the array using this method only.

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;
}

Check if array has at least two elements with specific value

Assume that I have an array with the following values: 0,1,0,0,0,1,0,1,1
I am currently looping over my array and replacing 1's with 0's. However I would to break out of this loop if there are 2 1's left in my array. I don't really have much in terms of code but this is a stub of what I've been working on
if(//There are more than 2 1s ){
return true; //carry on looping
}
return false; //break the loop
I have no idea how to differentiate between the 0's and the 1's and so I am quite confused with how to get this to work. Any ideas would be appreciated.
One possible solution is to start by writing a utility method to test if a given value at a specific position is unique from every subsequent position in the array like,
private static boolean testUnique(int[] arr, int i) {
int t = arr[i];
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] == t) {
return false;
}
}
return true;
}
Then you can iterate the array from the left to the right, checking if every value is unique like
public static boolean hasDuplicate(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if (!testUnique(arr, i)) {
return false;
}
}
return true;
}
Using your array,
public static void main(String[] args) {
int[] arr = { 0, 1, 0, 0, 0, 1, 0, 1, 1 };
System.out.println(hasDuplicate(arr));
}
That is false. Alternatively, you might find it easier if you first sort your array.
public int[] testDuplicatesofOne(int[] arr)
{
int count=0;
for(int i=0;i<arr.length-1;i++)
{
count+=(arr[i]>0?1:0);
}
if(count>=2)
{
for(int j=0;j<arr.length-1;j++)
{
if(count>2)
{
if(arr[j]==1)
{
arr[j]=0;
count--;
}
}else
{
break;
}
}
}
}
Hi Lukasz try this, Sorry if I have not understood your requirement properly.

Getting every combination of Queens?

public class SomeQueens {
static Stack<Integer> s= new Stack<Integer>();
static int Solved = 0;
static int current = 0;
public static int solve(int n) { // n is 8
while(current < n) { // should I use current < n instead
for (int i = current; i < n; i++) {
if(validPosition(i)) {
s.push(i);
current = 0;
}
}
if(!validPosition(current)) {
if(s.empty()) {
break;
}
if(!s.empty()) {
s.pop();
current++;
}
}
if(s.size() == n) {
s.pop();
current++;
printSolution(s);// this is a method, but it shouldn't matter for this
Solved++;
}
}
return Solved;
}
public static boolean validPosition(int column) {
for( int row = 0; row < s.size(); row++)
if(s.get(row) == column || ((column - s.get(row)) == (s.size() - row)) ||
((s.get(row) - column) == (s.size() - row)) )
return false; // there's a conflict
return true; // no conflict;
}
//it's called by int num = solve(n);
//sop("There're" + num + "sols to the" + n "queens prob");
This is a subsection of my program for NQueens, but I seem to always get: There are 0 solutions to the 8-queens problem. I tried debugging with system.out.prints in the main method, which led me to guess that there would be something wrong in my boolean method, but I don't think it's doing anything wrong.
I'm unsure if my while statement is incorrect or if the break inside the while loop is initialized before anything is even done. Thanks for the help and guidance and I'm sorry if my program and explanation makes no sense
Here is why you instantly get a zero:
s.push(0);
while(s.size() > n) // n is 8
{
//...
}
return Solved;
When the program arrives at the while-condition s has a size of one and n is 8. This will instantly fail and cause the method to return a zero.
But that's not the only problem with the algorithm. You should seriously rethink it.

Categories

Resources