recursion + bug at my main [duplicate] - java

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
I'm using java bluejay trying to solve a recursion problem.
The problem : given an array of natural numbers (higher then 0)
and an int, the method needs to tell if the array consist of a way to sum up the numbers to get the given int.
example {4,5} int = 13 >> 4+4+5 = 13 = true
example {4,5} int = 3 >>> false.
The 2nd problem is that when i use my main it says "cannot find symbol - method
isSumOf(int[],int) although i do have this kind of method...
Here is my classes:
public class Ex14
{
static int allways;
static int index = -1;
public static boolean isSumOf(int[] s, int n){
if(index == -1) index = s.length - 1;
return isSumOf(s, n, index);
}
private static boolean isSumOf(int[] s, int n, int index){
int temp = s[index];
if(allways == n) {return true;}
if(allways > n && index != 0) {allways -= temp + s[index - 1];
if(allways / s[index - 1] == s.length) index --;}
if(allways > n && index == 0) return false;
if(allways < n) allways += temp; return isSumOf(s, n);
}
}
My main class:
public class bdikot
{
public static void main(String[] args){
int [] hi= new int[1];
hi[0]=3;
System.out.println(isSumOf(hi,7));}
}
Thanks in advance Asaf :-) .

For your second problem, I think you need to change:
System.out.println(Ex14.isSumOf(hi,7));
Since isSumOf exists in a different class than your main method.
Also you might want to take a look at:
https://en.wikipedia.org/wiki/Programming_style
https://google.github.io/styleguide/javaguide.html
Since following these will make your code easier to read for others.

Related

What is wrong with this binary search? IndexOutOfBounds [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I'm trying to write the binary search algorithm, But Geeks for Geeks practice problem Binary Search yields following error:
Runtime Error:
Runtime ErrorException in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 222 out of bounds for length 5
at Solution.binarysearch(GFG.java:44)
at GFG.main(GFG.java:22)
What I've written so far is,
class Solution {
int binarysearch(int arr[], int n, int k){
if (arr == null) return -1;
int begin = 0;
int end = k;
for (; begin < end;)
{
int mid = (begin + end) / 2;
if (arr[mid] == n) return mid;
if (arr[mid] > n)
{
// in left part
begin = begin; // for debug
end = mid;
}
else
{
// in right part
begin = mid + 1;
end = end; // for debug
}
}
return -1;
}
}
Geeks for Geeks problem statement&example:
Given a sorted array of size N and an integer K, find the position at
which K is present in the array using binary search.
Example 1:
Input: N = 5 arr[] = {1 2 3 4 5} K = 4
Output: 3
Explanation: 4 appears at index 3.
Replace int end = k; to int end = n-1;
k is the number you have to find, n is the array size

Why doesnt my code compile, wanted to parseInt Fibonacci [duplicate]

This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 2 years ago.
I created a code for Fibonacci numbers, but it doesn't compile and I don't know why, can someone help.
(And I also think that the last like with k-1 + k-2 doesn't make any sense.
public class Fibonacci {
public static void main(String[] args) {
int n = Integer.parseInt(args[n]);
System.out.println(FibNum(n));
}
public static int FibNum(int k) {
if (k == 0) return 0;
if (k == 1) return 1; else return k - 1 + k - 2;
}
}
int n = Integer.parseInt(args[n]); how could it work? variable n in not initialized

Why I cannot get the correct number of candies using this program?

This exercise required us to write a program for counting the number of candies the poor kids can get. The question is shown below:
You are requested to write a Java program to help these poor kids to answer this question. To generalize the solution, your program should be able to accept different values of n and m as input, where n = 10 and m = 2 in this question. To avoid infinite number of answers, you may assume that each candy has exactly one foil and it is not allowed to cut the foils.
And I follow the hints given to write the program using the provided formula and java recursion.
import java.util.Scanner;
public class MyFirstClass{
public static void main(String args[]){
Scanner a=new Scanner(System.in);
int n=0,m=0;
n = a.nextInt();
m = a.nextInt();
System.out.println("Candy " +n+" "+ m + " n="+ n+";m="+m+";No. of Candies="+total(n,m));
}
static int sum=0;
static int total(int n, int m)
{
int sum1=n;
sum1+=candy(n,m);
return sum1;
}
static int candy(int n,int m){
if((n+n%m)/m>1){
sum+=n/m+candy((n+(n%m))/m,m);
}
return sum;
}
}
However, when I set n=10 and m=2, the calculated total number of candies is less than the actual total number of candies by 1. What is the problem of my program? Thank you!
For your candy function:
static int candy(int n,int m){
if((n+n%m)/m>1){
sum+=n/m+candy((n+(n%m))/m,m);
}
return sum;
}
How does it even compile when sum is undefined?
In any case, the candy function needs to check the boundary condition of of when the first paramater is 0 or 1. And I'll assume negative numbers aren't valid input either.
int candy(int n, int m) {
if ((n <= 1) || (m == 0)) {
return 0;
}
return n/m + candy( ((n+n%m)/m), m);
}
And since it's "tail recursion", you can implement the entire thing with a while loop:
int candy(int n, int m) {
int result = 0;
while ((n > 1) && (m != 0))
{
result += n/m;
n = (n+n%m)/m;
}
return result;
}

Minimum in Rotated Sorted Array ArrayIndexOutOfBoundsException [duplicate]

This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 7 years ago.
I found this problem on leetcode, I've solved it on my platform. For the tests I've used 1000 elements arrays, and never got an error. On leetcode platform it throws ArrayIndexOutOfBoundsException. If you look carefully, there is no way the elements a, b, or can n go further than array's length. This is the description of the problem:
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
You may assume no duplicate exists in the array.
public class Solution
{
public int findMin(int[] num)
{
int a = 0;
int b = num.length - 1;
int n = ( a + b ) / 2;
while ( true )
{
if ( num[n] < num[n+1] && num[n] < num[n-1] )
break;
if ( num[a] < num[b] )
{
b = n;
n = (a + n) / 2 + 1;
}
else
{
a = n;
n = ( b + n ) / 2;
}
}
return num[n];
}
}
public static int findMin(int[] num) {
return helper(num, 0, num.length - 1);
}
public static int helper(int[] num, int endLeft, int endRight) {
if (endLeft == endRight)
return num[endLeft];
if ((endRight - endLeft) == 1)
return Math.min(num[endLeft], num[endRight]);
int middleIndex = endLeft + (endRight - endLeft) / 2;
int middle = num[middleIndex]; // middle value
if (num[endLeft] < num[endRight]) {
return num[endLeft];
} else if (middle > num[endLeft]) {
// go right side
return helper(num, middleIndex, endRight);
} else {
// go left side
return helper(num, endLeft, middleIndex);
}
}
From coding interview.

Memoization with recursive method in java

I am working on a homework assignment, and I have completely exhausted myself. I'm new to programming, and this is my first programming class.
this is the problem:
Consider the following recursive function in Collatz.java, which is related to a famous unsolved problem in number theory, known as the Collatz problem or the 3n + 1 problem.
public static void collatz(int n) {
StdOut.print(n + " ");
if (n == 1) return;
if (n % 2 == 0) collatz(n / 2);
else collatz(3*n + 1);}
For example, a call to collatz(7) prints the sequence
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
as a consequence of 17 recursive calls. Write a program that takes a command-line argument N and returns the value of n < N for which the number of recursive calls for collatz(n) is maximized. Hint: use memoization. The unsolved problem is that no one knows whether the function terminates for all positive values of n (mathematical induction is no help because one of the recursive calls is for a larger value of the argument).
I have tried several things: using a for loop, trying to count the number of executions with a variable incremented each time the method executed, and hours of drudgery.
Apparently, I'm supposed to use an array somehow with the memoization. However, I don't understand how I could use an array when an array's length must be specified upon initiation.
Am I doing something completely wrong? Am I misreading the question?
Here is my code so far. It reflects an attempt at trying to create an integer array:
public class Collatz2 {
public static int collatz2(int n)
{
StdOut.print(n + " ");
if (n==1) {return 1;}
else if (n==2) {return 1;}
else if (n%2==0) {return collatz2(n/2);}
else {return collatz2(3*n+1);}
}
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
StdOut.println(collatz2(N));
}
}
EDIT:
I wrote a separate program
public class Count {
public static void main(String[] args) {
int count = 0;
while (!StdIn.isEmpty()) {
int value = StdIn.readInt();
count++;
}
StdOut.println("count is " + count);
}
}
I then used piping: %java Collatz2 6 | java Count
and it worked just fine.
Since you are interested in the maximum sequence size and not necessarily the sequence itself, it is better to have collatz return the size of the sequence.
private static final Map<Integer,Integer> previousResults = new HashMap<>();
private static int collatz(int n) {
int result = 1;
if(previousResults.containsKey(n)) {
return previousResults.get(n);
} else {
if(n==1) result = 1;
else if(n%2==0) result += collatz(n/2);
else result += collatz(3*n + 1);
previousResults.put(n, result);
return result;
}
}
The memoization is implemented by storing sequence sizes for previous values of n in Map previousResults.
You can look for the maximum in the main function:
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int maxn=0, maxSize=0;
for(int n=N; n>0; n--) {
int size = collatz(n);
if(size>maxSize) {
maxn = n;
maxSize = size;
}
}
System.out.println(maxn + " - " + maxSize);
}
The trick here is to write a recursive method where an argument is the value you want to "memoize". For instance, here is a version of a method which will return the number of steps needed to reach 1 (it supposes that n is greater than or equal to 1, of course):
public int countSteps(final int n)
{
return doCollatz(0, n);
}
public static int doCollatz(final int nrSteps, final int n)
{
if (n == 1)
return nrSteps;
final int next = n % 2 == 0 ? n / 2 : 3 * n + 1;
return doCollatz(nrSteps + 1, next);
}
If you were to record the different steps instead, you'd pass a List<Integer> as an argument and .add() to it as you went through, etc etc.

Categories

Resources