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;
}
}
Related
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).
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 am building a data structure to learn more about java. I understand this program might be useless.
Here's what I want. I want to create a data structure that store smallest 3 values. if value is high, then ignore it. When storing values than I also want to put them in correct place so I don't have to sort them later. I can enter values by calling the add method.
so let's say I want to add 20, 10, 40, 30 than the result will be [10,20,30]. note I can only hold 3 smallest values and it store them as I place them.
I also understand that there are a lot of better ways for doing this but again this is just for learning purposes.
Question: I need help creating add method. I wrote some code but I am getting stuck with add method. Please help.
My Thinking: we might have to use a Iterator in add method?
public class MyJavaApp {
public static void main(String[] args){
MyClass<Integer> m = new MyClass<Integer>(3);
m.add(10);
m.add(20);
m.add(30);
m.add(40);
}
}
public class MyClass<V extends Comparable<V>> {
private V v[];
public MyClass(int s){
this.v = (V[])new Object[s];
}
public void add(V a){
}
}
Here is a rough sketch of the add method you have to implement.
You have to use the appropriate implementation of the compareTo method when comparing elements.
public void add(V a){
V temp = null;
if(a.compareTo( v[0]) == -1 ){
/*
keeping the v[0] in a temp variable since, v[0] could be the second
smallest value or the third smallest value.
Therefore call add method again to assign it to the correct
position.
*/
temp = v[0];
v[0] = a;
add(temp);
}else if(a.compareTo(v[0]) == 1 && a.compareTo(v[1]) == -1){
temp = v[1];
v[1] = a;
add(temp);
}else if(a.compareTo(v[1]) == 1 && a.compareTo(v[2]) == -1){
temp = v[2];
v[2] = a;
add(temp);
}
}
Therefore the v array will contain the lowerest elements.
Hope this helps.
A naive, inefficient approach would be (as you suggest) to iterate through the values and add / remove based on what you find:
public void add(Integer a)
{
// If fewer than 3 elements in the list, add and we're done.
if (m.size() < 3)
{
m.add(a);
return;
}
// If there's 3 elements, find the maximum.
int max = Integer.MIN_VALUE;
int index = -1;
for (int i=0; i<3; i++) {
int v = m.get(i);
if (v > max) {
max = v;
index = i;
}
}
// If a is less than the max, we need to add it and remove the existing max.
if (a < max) {
m.remove(index);
m.add(a);
}
}
Note: this has been written for Integer, not a generic type V. You'll need to generalise. It also doesn't keep the list sorted - another of your requirements.
Here's an implementation of that algorithm. It consists of looking for the right place to insert. Then it can be optimized for your requirements:
Don't bother looking past the size you want
Don't add more items than necessary
Here's the code. I added the toString() method for convenience. Only the add() method is interesting. Also this implementation is a bit more flexible as it respects the size you give to the constructor and doesn't assume 3.
I used a List rather than an array because it makes dealing with generics a lot easier. You'll find that using an array of generics makes using your class a bit more ugly (i.e. you have to deal with type erasure by providing a Class<V>).
import java.util.*;
public class MyClass<V extends Comparable<V>> {
private int s;
private List<V> v;
public MyClass(int s) {
this.s = s;
this.v = new ArrayList<V>(s);
}
public void add(V a) {
int i=0;
int l = v.size();
// Find the right index
while(i<l && v.get(i).compareTo(a) < 0) i++;
if(i<s) {
v.add(i, a);
// Truncate the list to make sure we don't store more values than needed
if(v.size() > s) v.remove(v.size()-1);
}
}
public String toString() {
StringBuilder result = new StringBuilder();
for(V item : v) {
result.append(item).append(',');
}
return result.toString();
}
}
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);
}
}
I wrote this recursive method to find an integer in an integer array but it's not working. I tried debugging it but I don't know what the problem could be.
Here's the code
public static String inList(int[] primes,int a){
int index = -9;
if(primes.length>1){
index = primes.length/2;
}else{
if(primes[0] == a){
return "True";
}else{
return "False";
}
}
if(primes[index] == a){
return "True";
}
if(primes[index] > a){
inList(Arrays.copyOfRange(primes, 0, index),a);
}
if(primes[index]<a){
inList(Arrays.copyOfRange(primes, index, primes.length),a);
}
//shouldn't even get to this point, but eclipse insisted I needed another return
//statement
return "Whyyyyy?";
}
you have forgot to add return
did you sort your array?
if(primes[index] > a){
return inList(Arrays.copyOfRange(primes, 0, index),a);
}
if(primes[index]<a){
return inList(Arrays.copyOfRange(primes, index, primes.length),a);
}
Just use Arrays.binarySearch(). As you will see from its different prototypes, it will return a negative value if and only if the value you are looking for in the array is not there.
Recursive function to find something in an array would be:
public static String inList(int[] primes,int index, int a) {
/* two breaking conditions for recursion: end of array or number found */
if(index >= primes.length)
return "False";
if(primes[index] == a)
return "True";
/* recursion */
return inList(primes, ++index, a);
}
You can call above method with index = 0 ex. inList(primes, 0, a). This will be much slower than non-recursive find method.