public class App {
public static int start;
public static int end;
public static int search(int nums[],int target) {
System.out.println("entered search");
start=0;
end=nums.length-1;
int max=maxSearch(nums);
System.out.println("reentered search");
if(target>=nums[start]&&target<=nums[max]) {
end=max;
} else if(target>=nums[max+1]&&target<=nums[end]) {
start=max+1;
}
return (binarysearch(nums,target));
}
public static int binarysearch(int nums[],int target) {
int mid=start+(end-start)/2;
System.out.println("entered binarysearch");
while(start<end) {
if(target==nums[mid])
return mid;
if(target>nums[mid])
start=mid+1;
if(target<nums[mid])
end=mid-1;
}
return end;
}
public static int maxSearch(int nums[]) {
start=0;
end=nums.length-1;
System.out.println("entered maxSearch");
while(start<end) {
int mid=start+(end-start)/2;
if(nums[mid+1]<nums[mid])
return mid;
if(nums[mid]>nums[start])
start=mid+1;
if(nums[mid]<nums[start])
end=mid-1;
}
return end;
}
public static void main(String args[]) {
int nums[]={4,5,6,7,0,1,2};
int target=7;
System.out.println(search(nums, target));
}
}
In this, I am trying to get the index of the target. The array was an originally sorted array in ascending order. It is now rotated around an index. My programme is not printing any value for target 6 and 7 . However for the rest of the numbers, it is working alright and is giving accurate value. For example, for 4, it giving index 0 after printing the lines telling flow of control but for 6 and 7, it doesn't print any index. Can you point out what is wrong here? I want to have logn time complexity.
I was first finding the maximum number in the array(ma search) , because the left part and right part of the array is sorted since a sorted array is rotated around an index originally like [0,1,2,4,5,6,7] is rotated around index 3. Then, I checked that in which part left or right, can my target be present(Search) and at last I performed a binary search on that part(binary search).
Related
I struggle with this coding "challenge".
I need to look for the original value in nums. If its there, multiply by two
and redo the whole thing.
Return the value if there is no more same value.
It works on a lot of test cases but I get a weird error with this set while debugging.
After I iterate the array and was ready to return the right value, instead of returning the 16, it calls the findFinalValue again and iterates itself from 16 down again to 4.
public class Main {
public static void main(String[] args) {
Solution s = new Solution();
int[] nums = {8,19,4,2,15,3};
System.out.println(s.findFinalValue(nums, 2));
}
}
class Solution {
public int findFinalValue(int[] nums, int original) {
for(int n: nums){
if(n == original){
original*=2;
findFinalValue(nums, original);
}
}
return original;
}
}
It is not iterating from 16 to 4, it is how recursion works. You need to pass the result back or store it in a global variable. Once the dead-end is achieved in recursion it backtracks and comes back to its original state.
Solution
class Solution {
public int findFinalValue(int[] nums, int original) {
int isPresent = false;
for(int n: nums){
if(n == original){
isPresent = true;
break;
}
}
if(isPresent) {
original = findFinalValue(nums, original*2);
}
return original;
}
}
Frankly speaking, you can optimize it by sorting the array at first and then using binary search for finding elements, in addition, the array passed in the next state can be reduced till the index has read. Because original has become twice
I wouldn't use recursion, but since I think you're asking about a recursive solution, I would do it like this:
public int findFinalValue(int[] nums, int original) {
return IntStream.of(nums).anyMatch(n -> n == original)
? findFinalValue(nums, 2 * original)
: original;
}
Guessing that your problem is that your have not implemented recursion properly:
class Solution {
public int findFinalValue(int[] nums, int original) {
int found = original;
for(int n: nums){
if(n == original){
found = findFinalValue(nums, found * 2);
}
}
return found;
}
}
public class linklist {
public static void main(String[] args) {
int a = 00486;
int x=zero(a);
System.out.println(x);
}
public static int zero(int n)
{
if(n<=10)
{
return 0;
}
if(n%10==0) {
return 1 + zero(n / 10);
}
else
return zero(n/10);
}
}
in line 3 i set 00486 as value but its showing integer too large error.As per my knowledge In Java, the integer value permissible is much bigger.
When you add 0 in front of the number, it is treated in the octal format. In octal format, the allowed digits vary from 0 to 7 only .
Therefore, you need to change the number from 00486 to 00476. But be beware, this number will be converted to base 10 format. To verify that, I have written a print statement that shows that the number will be stored indeed in base 10 format.
public class linklist {
public static void main(String[] args) {
int a = 0476;
System.out.println(8*8*4 + 8*7 + 6);
System.out.println(a);
int x=zero(a);
System.out.println(x);
}
public static int zero(double n)
{
if(n<=10)
{
return 0;
}
if(n%10==0) {
return 1 + zero(n / 10);
}
else
return zero(n/10);
}
}
I was trying to execute the below code. It ran without any compilation errors. But the remove(int index) method is not working as expected.
import java.util.*;
public class Stones {
static int findLastStoneWeight(ArrayList<Integer> weight)
{
while(true)
{
Collections.sort(weight);
int n=weight.size();
if (n==1)
return weight.get(0);
else if(weight.get(n-1)>weight.get(n-2))
{
int temp1=weight.get(n-1);
int temp2=weight.get(n-2);
weight.add(n-2,temp1-temp2);
weight.remove(n-1);
System.out.println(weight.size()); //The new size of weight should be decreased by 1 but it does not!!
}
else
{
weight.remove(n-1);
weight.remove(n-2);
}
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
ArrayList<Integer> weight=new ArrayList<Integer>();
System.out.println("Enter the weights:");
while(true)
{
int w=sc.nextInt();
if(w<0)
break;
weight.add(w);
}
int lswt=findLastStoneWeight(weight);
System.out.println("Last stone weight:"+lswt);
}
}
When I used the remove(int index) method on the ArrayList weight the size of the ArrayList should get reduced by 1 but it remains the same. Why?
in the else if branch you noted, you first add an element to the weight ArrayList:
weight.add(n-2,temp1-temp2);
and then remove an element:
weight.remove(n-1);
All in all, you've added an element and removed an element, so the size of the list at the end of the method will be same as it was in the metho'd begining.
I'm doing a binary search on an array. But somethings to be off. It returns -1 as if the target is not being found but it is in the array.
ex: when I put the key at 555 it returns the correct index but when I try with the example below with 8 it returns -1..
public class bSearch {
public static void main(String[] args) {
int[] nums = {9,5,2,5,7,8,3,22,555};
int key = 8;
System.out.println(searchForNum(nums,0,nums.length-1,key));
}
private static int searchForNum(int[] arr,int first, int last, final int target) {
int middle= (first+last)/2;
if(last < first) {
return -1;
}
if(arr[middle]== target)
return middle;
else if(target < arr[middle]) {
return searchForNum(arr,first,middle-1,target);
} else {
return searchForNum(arr,middle+1,last,target);
}
}
}
The reason why binary search works is that the search interval is ordered. You are passing an unordered interval, which leads to search errors.
Call Arrays.sort on your data array before searching:
int[] nums = {9,5,2,5,7,8,3,22,555};
Arrays.sort(nums);
You can not do binary search without sorting the list/array that you want to search on it
please read this for more info binary-search.
you need to modified your main method to be
public static void main(String[] args) {
int[] nums = {9,5,2,5,7,8,3,22,555};
int key = 8;
Arrays.sort(nums); // sort the array
System.out.println(searchForNum(nums,0,nums.length-1,key));
}
I'm trying to write a recursive method that accepts an int array, number of elements in the array, and an integer, and returns whether the integer is present as an element in the array.I just can't figure out why I this isn't working for all my test cases. Any help would be much appreciated!
public static boolean search(int[] findIn, int target, int len){
if(len == 0){
return false;
}else if(findIn[len-1] == target){
return true;
}else{
return search(findIn, target, len-1);
}
}
Yes I realize there are better ways other than recursion to do this, but it is required that I do it this way.
My main method looks like this: I'm just hard-coding it for the time being:
int[] arr = {1};
System.out.println(search(arr,1,1));
Testcases:
I am almost certain, that your method parameters are in the wrong order:
Your results hint that you switched the 2nd and 3rd parameter!
Maybe this
static boolean search(int[] findIn, int target, int len)
should actually be
static boolean search(int[] findIn, int len, int target)
From what I can see, that code should work fine so I suspect your problem lies in your test cases rather than here.
One thing I will mention is that use of if-return-else constructs tend to complicate your code unnecessarily.
It's usually better to avoid that with something like:
public static boolean search(
int[] findIn, int target, int len)
{
if (len == 0)
return false;
if (findIn[len-1] == target)
return true;
return search(findIn, target, len-1);
}
I find that a lot easier to follow at a glance than trying to track what if clause I happen to be in at any given moment.
In any case, both it and your version perform fine, at least for small test cases. The first time you pass in a ten-million-element array is probably when you'll discover it's not the best poster child for recursion.
I tried something like this and it is working..
I am using a static instance variable to find the position of number in array.
In stead of returning the position of number you can modify to return a boolean
public class RecSearch {
static int pos=0;
public static void main(String[] args) {
int a[] = {1};
System.out.println(recSearch(a, 0));
System.out.println(recSearch(a, 1));
}
public static int recursiveSearch(int[] arr, int numtoSearch) {
if (pos>=arr.length) {
pos=0;
return -1;
}
if (arr[pos]==numtoSearch)
return (pos+1);
else {
pos++;
return recursiveSearch(arr, numtoSearch);
}
}
}
public class Solution {
public static boolean checkNumber(int input[], int x) {
return check(input,x,0);
}
public static boolean check(int input[],int x,int start){
if(start==input.length)
return false;
if(input[start]==x)
return true;
return check(input,x,start+1);
}
}