I am attempting to create a recursive method that accepts an integer parameter and prints the first n squares
separated by commas, with the odd squares in descending order followed by the even squares in ascending order.
For example, if the input is 8, it should print the following output:
49, 25, 9, 1, 4, 16, 36, 64
My code so far is:
s and n have the same values initially, the only difference is that s changes as the code forwards while n doesn't change.
private static void genSquare(int s, int n) {
if (s >= 0 && s <= n) {
if (isOdd(s)) {
System.out.print(Math.pow(n, 2) + " ");
genSquare(s - 2, n);
}
if (s == 0 || s == 1) {
genSquare(1, n);
}
if (isEven(s)) {
System.out.print(Math.pow(n, 2) + " ");
genSquare(s + 2, n);
}
}
}
I have created a while loop version of it, which works perfectly. I just don't have the recursive version working.
Sample inputs would be using the same number for s and n.
Here is the code for the loop version:
private void genLoop(int s, int n) {
if (isEven(s)) {
s--;
}
while (s <= n) {
if (s == 1) {
System.out.print(1 + " ");
s++;
} else if (isOdd(s)) {
System.out.print(s * s + " ");
s -= 2;
} else if (isEven(s)) {
System.out.print(s * s + " ");
s += 2;
}
}
}
The problem is in this statement:
if(s == 0 || s== 1)
genSquare(1,n);
This causes the method to recurse infinitely. In fact, when you get to the point where s is zero or one, you have to make sure that you DON'T call genSquare recursively.
That's enough of a hint for you to figure the rest out for yourself ... and fix any other bugs.
In addition, there's a simpler way of squaring an integer ...
void calculateSquare(int n)
{
// odds descending and even ascending
int t=n;
if(n<=0)
return;
if(n%2==1)
{
// Calculate square now and print it also
System.out.println(n*n);
calculateSquare(--n);
}
else
{
calculateSquare(--n);
System.out.println(t*t);
}
}
This would do the job.
Try the following approach:
Assume your example where n is equal to 8. The square of 8 should printed last so you probably first should do a recursive call, then print the square of the current number.
Thinking about the task for n=7 the order of things given above should be reverted for odd numbers.
Yes it is good example for recursion . Try this it helps u
public class RecursionEx {
static int no = 0;
public static void main(String[] args) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number");
try
{
no = Integer.parseInt(bufferedReader.readLine());
getSquares(no,0);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void getSquares(int number,int count)
{
if(number==1)
{
System.out.print(number);
count=1;
getSquares(number+1, count);
}
else
{
if(number%2!=0&&count==0)
{
System.out.print(number*number+",");
getSquares(number-2,0);
return;
}
if(count==0)
getSquares(number-1,0);
if(number%2==0&&count==1)
{
if(number<=no)
System.out.print(","+number*number);
if(number>=no)
return;
getSquares(number+2, count);
}
}
}
}
Related
The first for loop prints the proper coeffcient and exponent values as
provided by the value string, but the second for loop which class the
addLink method does not print the proper values? I cannot see what the
problem is. Why does the output from the first for loop not match the output from the second?
The code has been edited. I have moved the addLink method into the first for loop and my output is shown below. it is still not what I am intending.
public class Polyvalues {
Term head;
public Polyvalues() {
String value = "5 6 8 9 1 9";
String sub[] = value.split(" ");
double coeff = 0;
int exp = 0;
for (int i = 0; i < sub.length; i++)
{
if (sub[i].isEmpty()) {
System.out.println("No input");
}
if (i % 2 == 0) {
try {
coeff = Double.parseDouble(sub[i]);
System.out.println("Coeff is " + coeff);
} catch (NumberFormatException e) {
System.out.println("Fix This");
}
} else {
try {
exp = Integer.parseInt(sub[i]);
System.out.println("The exp is " + exp);
} catch (NumberFormatException e) {
System.out.println("Fix This");
}
}
this.addLink(coeff, exp);//moved from commented out for-loop
}
System.out.println("*******************************************");
/*for (int i = 0; i < sub.length; i++)
{
this.addLink(coeff, exp);
}*/
}//end constructor
public void addLink(double a, int b)
{
if(head == null)
{
head = new Term(a,b);
return;
}
Term currNode = head;
while(currNode.next != null)
{
currNode = currNode.next;
}
currNode.next = new Term(a,b);
//addLink(a,b);
}
static class Term{
double coeff;
int exp;
Term next;
Term(double c, int e){
this.coeff = c;
this.exp = e;
this.next = null;
System.out.println("The Coeff "+ this.coeff);
System.out.println("The Exp "+ this.exp);
}
}
public static void main(String[] args)
{
Polyvalues p1 = new Polyvalues();
}
} //end of class
Now, I get this when I move the addLink method into the first for-loop. Why am I getting these duplicate outputs when I print?
When this is what I want:
Is it my nodes?
Because in the second loop you are passing the same value of coeff and exp every time.
At the end of your first loop value of coeff is 1.0 and exp is 9
and you are passing that same value every time, in the second loop, to method addLink.
To solve it either make an array to store every value or just call addLink in the first loop.
You really need to learn how to debug your code. Every programmer needs to know how to debug code. Have you read this Web page? How to debug small programs
In any case, if you are using an IDE (like Eclipse or IntelliJ) then it should have a debugger and you should learn to use it.
You are close with your code. You just need to move the call to method addLink. (See the below code.) If you step through the code using a debugger, you will understand why. Basically you need to call addLink after you have obtained a value for both coeff and exp. In your code you are calling addLink twice – once when you only have the coeff value and the second time when you have both coeff and exp.
In the below code, I have indicated the change with the comment Moved from after this 'else' block. I also left the original line but commented it out.
Also note that I added [overridden] toString methods just to make it easier to see the results of executing the code.
public class Polyvalues {
Term head;
public Polyvalues() {
String value = "5 6 8 9 1 9";
String sub[] = value.split(" ");
double coeff = 0;
int exp = 0;
for (int i = 0; i < sub.length; i++) {
if (sub[i].isEmpty()) {
System.out.println("No input");
}
if (i % 2 == 0) {
try {
coeff = Double.parseDouble(sub[i]);
System.out.println("Coeff is " + coeff);
}
catch (NumberFormatException e) {
System.out.println("Fix This");
}
}
else {
try {
exp = Integer.parseInt(sub[i]);
System.out.println("The exp is " + exp);
this.addLink(coeff, exp); // Moved from after this 'else' block.
}
catch (NumberFormatException e) {
System.out.println("Fix This");
}
}
//this.addLink(coeff, exp);//moved from commented out for-loop
}
System.out.println("*******************************************");
}// end constructor
public void addLink(double a, int b) {
if (head == null) {
head = new Term(a, b);
return;
}
Term currNode = head;
while (currNode.next != null) {
currNode = currNode.next;
}
currNode.next = new Term(a, b);
// addLink(a,b);
}
public String toString() {
StringBuilder sb = new StringBuilder();
Term curr = head;
while (curr != null) {
sb.append(curr);
curr = curr.next;
}
return sb.toString();
}
static class Term {
double coeff;
int exp;
Term next;
Term(double c, int e) {
this.coeff = c;
this.exp = e;
this.next = null;
System.out.println("The Coeff " + this.coeff);
System.out.println("The Exp " + this.exp);
}
public String toString() {
return String.format("[C=%.2f,E=%d]-> ", coeff, exp);
}
}
public static void main(String[] args) {
Polyvalues p1 = new Polyvalues();
System.out.println(p1);
}
} // end of class
Running the above code prints the following:
Coeff is 5.0
The exp is 6
The Coeff 5.0
The Exp 6
Coeff is 8.0
The exp is 9
The Coeff 8.0
The Exp 9
Coeff is 1.0
The exp is 9
The Coeff 1.0
The Exp 9
The Coeff 1.0
The Exp 9
*******************************************
[C=5.00,E=6]-> [C=8.00,E=9]-> [C=1.00,E=9]-> [C=1.00,E=9]->
Something in the main function is wrong, but I don't know what. If I go through the code with a debugger I can see that my code isn't even reaching the fibonacci function right now.
public class Fibonacci {
public static void main(String[] args) {
for (int n=1; n<50; n++) {
System.out.println("Element "+ n + " of the sequence: " + newFib(n));
}
}
public static ArrayList<BigInteger> memo = new ArrayList<BigInteger>();
static BigInteger newFib(int n){
assert n >= 1: "the fibonacci sequence starts at 1";
BigInteger result=BigInteger.valueOf(1);
if (memo.get(n) != null) {
return memo.get(n);
}
else if( n == 1 || n == 2 ) {
memo.add(n, BigInteger.valueOf(1));
return BigInteger.valueOf(1);
}
else {
result= newFib(n-1).add(newFib(n-2));
memo.add(n,result);
return result;
}
}
}
Your code was throwing some exceptions. You simply needed to debug the exceptions and implement the proper checks. Using the code with these changes should work as intended:
import java.math.*;
import java.util.ArrayList;
public class Fibonacci {
public static void main(String[] args) {
for (int n=1; n<50; n++) {
System.out.println("Element "+ n + " of the sequence: " + newFib(n));
}
}
public static ArrayList<BigInteger> memo = new ArrayList<BigInteger>();
static BigInteger newFib(int n){
assert n >= 1: "the fibonacci sequence starts at 1";
BigInteger result=BigInteger.valueOf(1);
if (memo.size() - 1 >= n && memo.get(n) != null) {
return memo.get(n);
}
else if( n == 1 || n == 2 ) {
memo.add(n-1, BigInteger.valueOf(1));
return BigInteger.valueOf(1);
}
else {
result= newFib(n-1).add(newFib(n-2));
memo.add(n,result);
return result;
}
}
}
Your current code does not handle out of bounds correctly and as I mentioned in the comments, the fibonacci sequence does not necessarily start at one and the logic can be simplified. I would use a HashMap<Integer, BigInteger> for storing the memoization and I would also prefer to populate the initial constants once (and as constants). For example,
private static Map<Integer, BigInteger> memo = new HashMap<>();
static {
memo.put(0, BigInteger.ZERO);
memo.put(1, BigInteger.ONE);
}
static BigInteger newFib(int n) {
if (!memo.containsKey(n)) {
if (n < 0) {
memo.put(n, newFib(n + 2).subtract(newFib(n + 1)));
} else {
memo.put(n, newFib(n - 2).add(newFib(n - 1)));
}
}
return memo.get(n);
}
Which can then be tested like
public static void main(String[] args) {
for (int i = -8; i < 9; i++) {
if (i != -8) {
System.out.print(" ");
}
System.out.printf("%-5s", String.format("F(%d)", i));
}
System.out.println();
for (int i = -8; i < 9; i++) {
if (i != -8) {
System.out.print(" ");
}
System.out.printf("%-5s", newFib(i));
}
}
To reproduce the example given in the Fibonacci number Wikipedia entry.
F(-8) F(-7) F(-6) F(-5) F(-4) F(-3) F(-2) F(-1) F(0) F(1) F(2) F(3) F(4) F(5) F(6) F(7) F(8)
-21 13 -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13 21
My code results with endless number "2", I don't understand why.
Also my tutor told me to add validation for negative values - I don't know how to do it.
public class FibonacciRecursive {
public static void main(String[] args) {
int fibonacciNumberOrder = 10;
do {
System.out.print(fibonacci(fibonacciNumberOrder) + " ");
} while (true);
}
public static long fibonacci(int fibonacciNumberInOrder) {
if (fibonacciNumberInOrder == 0) {
return 0;
}
if (fibonacciNumberInOrder <= 2) {
return 1;
}
long fibonacci = fibonacci(-1) + fibonacci(-2);
return fibonacci;
}
}
edit:
When I changed that line
long fibonacci = fibonacci(-1) + fibonacci(-2);
to:
long fibonacci = fibonacci(fibonacciNumberInOrder-1) + fibonacci(fibonacciNumberInOrder-2);
It prints endless "55"
How should I change my code to make it work?
It happens because you calculate the Fibonacci number with constants instead of relative numbers to passed ones through, which is the point of recursion.
public static long fibonacci(int fibonacciNumberInOrder) {
if (fibonacciNumberInOrder == 0) {
return 0;
}
if (fibonacciNumberInOrder <= 2) {
return 1;
}
long fibonacci = fibonacci(fibonacciNumberInOrder - 1) + fibonacci(fibonacciNumberInOrder - 2);
return fibonacci;
}
The key changed line is:
long fibonacci = fibonacci(fibonacciNumberInOrder-1) + fibonacci(fibonacciNumberInOrder-2);
You are recursing with constants! Change this
long fibonacci = fibonacci(-1) + fibonacci(-2);
to
long fibonacci = fibonacci(fibonacciNumberInOrder-1) + fibonacci(fibonacciNumberInOrder-2);
And, in your while loop in main - you need to modify fibonacciNumberInOrder
int fibonacciNumberOrder = 1;
do {
System.out.print(fibonacci(fibonacciNumberOrder) + " ");
fibonacciNumberOrder++;
} while (true);
I need help to design java code for generating bit array for any given integer in following manner:
23 should produce output as 1101011 (min length array)
explaination :
positions are given as 1 -2 4 -8 16 -32 ....
So 1101011 can be evaluated as:
1*1 + 1*-2 + 0*4+ 1*-8 + 0*16 +1*-32 + 1*64 = 23
This is the so-called negabinary representation of numbers (described first by Vittorio Grünwald in 1885). They can be encoded in a fashion very similar to the usual binary representation, just working with -2 instead of 2 as base (Java code inspired by C# code on https://en.wikipedia.org/wiki/Negative_base ):
class EncodeNegaBinary {
public static void main(String[] args) {
int n=0,input=0;
String result="";
final String[] BITS = { "0","1" };
if (args.length != 1) {
System.err.println("Please enter an integer to be converted");
return;
} else {
input = n = Integer.parseInt(args[0]);
}
while (n != 0) {
int r = n%-2;
n /= -2;
if (r == -1) {
r=1;
n++;
}
result = BITS[r] + result;
}
System.out.printf( "%d -> %s\n", input, result);
}
}
Since it is not usual int to binary conversion, at each step we need to consider two cases as at each position there can be only two choices 0 or 1. This is done recursively in the below program:
public class ModifiedIntToBinaryConversion{
public static int calcBinaryString(int reqSum, int currSum, int add, String bs) {
if (reqSum == currSum) { // base condtion 1
System.out.println("The string is \n" + bs);
return currSum;
}
if (add + currSum > reqSum) { // base condtion 2
return 0;
}
int newAdd = add * -2;
// System.out.println("new add is "+ newAdd +" currSum is "+ currSum);
int s1 = calcBinaryString(reqSum, currSum + add, newAdd, bs + "1");
if (s1 == reqSum)
return s1;
int s2 = calcBinaryString(reqSum, currSum, newAdd, bs + "0");
return s2;
}
public static void calcBinaryString(int sum) {
int s1 = calcBinaryString(sum, 0, 1, "");
if(s1 != sum) {
System.out.println("The binary equivalent couldn't be found");
}
}
public static void main(String[] args) {
calcBinaryString(23);
}
}
Now base condition 1 is clear as I am just checking whether required sum and calculated sum are equal.
For base condition 2, I will accept it's result of debugging and a bit of thought as I was getting Stackoverflow errors. Once the calculated sum becomes greater than the required sum and then we take the next -ve number so that it become less than req. sum. But then the next +ve number will be greater than the -ve number we just considered and thus the chances are very less that the calculated sum will ever be equal to req. sum.
Question:
In this problem, the scenario we are evaluating is the following: You're standing at the base of a staircase and are heading to the top. A small stride will move up one stair, and a large stride advances two. You want to count the number of ways to climb the entire staircase based on different combinations of large and small strides. For example, a staircase of three steps can be climbed in three different ways: three small strides, one small stride followed by one large stride, or one large followed by one small.
The call of waysToClimb(3) should produce the following output:
1 1 1,
1 2,
2 1
My code:
public static void waysToClimb(int n){
if(n == 0)
System.out.print("");
else if(n == 1)
System.out.print("1");
else {
System.out.print("1 ");
waysToClimb(n - 1);
System.out.print(",");
System.out.print("2 ");
waysToClimb(n - 2);
}
}
My output:
1 1 1,
2,
2 1
My recursion doesn't seem to remember the path it took any idea how to fix it?
Edit:
Thank you guys for the responses. Sorry for the late reply
I figured it out
public static void waysToClimb(int n){
String s ="[";
int p=0;
com(s,p,n);
}
public static void com(String s,int p,int n){
if(n==0 && p==2)
System.out.print(s.substring(0,s.length()-2)+"]");
else if(n==0 && p !=0)
System.out.print(s+"");
else if(n==0 && p==0)
System.out.print("");
else if(n==1)
System.out.print(s+"1]");
else {
com(s+"1, ",1,n-1);
System.out.println();
com(s+"2, ",2,n-2);
}
}
If you explicity want to print all paths (different than counting them or finding a specific one), you need to store them all the way down to 0.
public static void waysToClimb(int n, List<Integer> path)
{
if (n == 0)
{
// print whole path
for (Integer i: path)
{
System.out.print(i + " ");
}
System.out.println();
}
else if (n == 1)
{
List<Integer> newPath = new ArrayList<Integer>(path);
newPath.add(1);
waysToClimb(n-1, newPath);
}
else if (n > 1)
{
List<Integer> newPath1 = new ArrayList<Integer>(path);
newPath1.add(1);
waysToClimb(n-1, newPath1);
List<Integer> newPath2 = new ArrayList<Integer>(path);
newPath2.add(2);
waysToClimb(n-2, newPath2);
}
}
initial call: waysToClimb(5, new ArrayList<Integer>());
Below mentioned solution will work similar to Depth First Search, it will explore one path. Once a path is completed, it will backtrace and explore other paths:
public class Demo {
private static LinkedList<Integer> ll = new LinkedList<Integer>(){{ add(1);add(2);}};
public static void main(String args[]) {
waysToClimb(4, "");
}
public static void waysToClimb(int n, String res) {
if (ll.peek() > n)
System.out.println(res);
else {
for (Integer elem : ll) {
if(n-elem >= 0)
waysToClimb(n - elem, res + String.valueOf(elem) + " ");
}
}
}
}
public class Test2 {
public int climbStairs(int n) {
// List of lists to store all the combinations
List<List<Integer>> ans = new ArrayList<List<Integer>>();
// initially, sending in an empty list that will store the first combination
csHelper(n, new ArrayList<Integer>(), ans);
// a helper method to print list of lists
print2dList(ans);
return ans.size();
}
private void csHelper(int n, List<Integer> l, List<List<Integer>> ans) {
// if there are no more stairs to climb, add the current combination to ans list
if(n == 0) {
ans.add(new ArrayList<Integer>(l));
}
// a necessary check that prevent user at (n-1)th stair to climb using 2 stairs
if(n < 0) {
return;
}
int currStep = 0;
// i varies from 1 to 2 as we have 2 choices i.e. to either climb using 1 or 2 steps
for(int i = 1; i <= 2; i++) {
// climbing using step 1 when i = 1 and using 2 when i = 2
currStep += 1;
// adding current step to the arraylist(check parameter of this method)
l.add(currStep);
// make a recursive call with less number of stairs left to climb
csHelper(n - currStep, l, ans);
l.remove(l.size() - 1);
}
}
private void print2dList(List<List<Integer>> ans) {
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans.get(i).size(); j++) {
System.out.print(ans.get(i).get(j) + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Test2 t = new Test2();
t.climbStairs(3);
}
}
Please note this solution will timeout for larger inputs as this isn't a memoized recursive solution and can throw MLE(as I create a new list when a combination is found).
Hope this helps.
if anyone looking for a python solution, for this problem.
def way_to_climb(n, path=None, val=None):
path = [] if path is None else path
val = [] if val is None else val
if n==0:
val.append(path)
elif n==1:
new_path = path.copy()
new_path.append(1)
way_to_climb(n-1, new_path, val)
elif n>1:
new_path1 = path.copy()
new_path1.append(1)
way_to_climb(n-1, new_path1, val)
new_path2 = path.copy()
new_path2.append(2)
way_to_climb(n-2, new_path2, val)
return val
Note: it is based on the #unlut solution, here OP has used a top-down recursive approach. This solution is for all people who looking for all combination of staircase problem in python, no python question for this so i have added a python solution here
if we use a bottom-up approach and use memorization, then we can solve the problem faster.
Even though you did find the correct answer to the problem with your code, you can still improve upon it by using just one if to check if the steps left is 0. I used a switch to check the amount of steps taken because there are only 3 options, 0, 1, or 2. I also renamed the variables that were used to make the code more understandable to anyone seeing it for the first time, as it is quite confusing if you are just using one letter variable names. Even with all these changes the codes run the same, I just thought it might be better to add some of these things for others who might view this question in the future.
public static void climbStairsHelper(String pathStr, int stepsTaken, int stepsLeft)
{
if(stepsLeft == 0)
{
switch(stepsTaken)
{
case 2:
System.out.print(pathStr.substring(0, pathStr.length() - 2) + "]");
break;
case 1:
System.out.print(pathStr + "");
break;
case 0:
System.out.print("");
break;
}
}
else if(stepsLeft == 1)
{
System.out.print(pathStr + "1]");
}
else
{
climbStairsHelper(pathStr + "1, ", 1, stepsLeft - 1);
System.out.println();
climbStairsHelper(pathStr + "2, ", 2, stepsLeft - 2);
}
}`
`