Printing asterisks using recursion - java

A method, printStars(j), is available that returns a string -- a row of j asterisks. I need to write a method that recursively prints a triangle of n rows of asterisks. The first row needs to have one *, the second have two *s, etc. No iterative loops can be used (so no while, do-while, or for).
The code to do it backwards is simple enough:
public void printTriangle(int n) {
if(n >= 1) {
printStars(n));
printTriangle(n - 1);
}
}
My code thus far for the above but reversed is below. It is incorrect as i is reset to 1 in each loop. I'm just not sure how to go about it. I can only use a one-parameter function.
public void printTriangle(int n) {
int i = 1;
if(i <= n) {
printStars(i);
printTriangle(i + 1);
}
}

Just first recur, then print the line:
public void printTriangle(int n) {
if(n > 1) {
printTriangle(n - 1);
}
System.out.println(makeStars(n));
}
So the smaller triangle is printed first, and then the longer line appended.

static int i = 1;
This will ensure that i retains its value between calls to the function.
It is initialized to 1 the first time, and any changes made to the variable will persist across calls.
EDIT: As the comment says, this isn't the right way. Daniel Fischer's solution is better.

Pass the maximum value of i as a second parameter to limit the number of lines to print i.e. the maximum value for i.

Maybe a two parameters function:
public void printTriangle(int i, int n) {
if(i <= n) {
System.out.println(printStars(i));
printTriangle(i+1, n);
}
}

Related

understanding recursion for dot product in java

Could anyone give me some clue about how could I Transform this code to recursion:
public class arrayExample {
public static void main (String[] args) {
int[] a = {2,2,2,2};
int[] b = {2,2,2,2};
int n = a.length;
int sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i] * b[i];
}
System.out.println(sum);
}
}
So to do this do product with recursion.
You asked for a hint, so I'm not giving you the complete solution. When you want to process a list (or an array) recursively, the concept is nearly always:
public int recursiveFunction(List l, int carry) {
if (l.isEmpty()) {
return carry;
}
return recursiveFunction(l.subList(1, l.size()), operation(carry, l.get(0));
}
Where operation is whatever you want to do with your list. carry is used to provide an initial value (in the first call) and save the interim results.
You just have to change the code so it uses two arrays instead of one list and choose the correct operation.
Ok so hoping you have tried it before this is one possible way to code it.
public class ArrayExample {
public static void main (String[] args) {
int[] a = {2,2,2,2};
int[] b = {2,2,2,2};
int n = a.length;
int result = recurseSum(a, b, n-1);
System.out.println(result);
}
public static int recurseSum(int[] a, int[] b, int n){
if(n == 0)
return a[0]*b[0];
else{
return (a[n] * b[n]) + recurseSum(a,b,n-1);
}
}
}
This code is basically doing the same thing in the iteration.
The recursive call happens 4 times. When n hits 0, a[0]*b[0] is returned to the higher call. so basically from right to left it happens as follows:
a[3]*b[3] + a[2]*b[2] + a[1]*b[1] + a[0]*b[0]
One simple way to make a loop into a recursion is to answer these two questions:
What happens when the loop executes zero times?
If the loop has already executed n-1 times, how do I compute the result after the n-th iteration?
The answer to the first case produces your base case; the answer to the second question explains how to do the recursive invocation.
In your case, the answers are as follows:
When the loop executes zero times, the sum is zero.
When the loop executed n-1 times, add a[n] * b[n] to the previous result.
This can be translated into a recursive implementation
static int dotProduct(int[] a, int[] b, int n) {
... // your implementation here
}

java Simple recursion

So there is a recursive method (can not use any loop), that has one parameter n, and the program will print out 2^n "*", for example, if n was 2, the output is ****, and if n was 3, the output is ********.
I'm stuck with this problem because I ran into some infinite recursion issues.
First I had this: but I soon realize that n will never reach the check.
↑↑↑ That was supposed to be n+1 (even though it doesn't work)
Then I tried this:
public class test {
public static void main(String[] args) {
printPowerOfTwoStars(3);
}
public static void printPowerOfTwoStars(int n){
n = (int)Math.pow(2, n);
if(n == 0){
return;
}
else{
System.out.print("*");
printPowerOfTwoStars(n-1);
}
}
}
Ran into some infinite recursion again.
This seems like a simple program with simple logic, but I'm having trouble with the condition check, because what's being compared with n keeps changing.
How should I fix this problem?
Without using any helper method or creating any static variables.
Thank you
You need to use the fact that 2 to the power of n is just 2 to the power of n-1, doubled. Your base case is that 2 to the power of 0 is 1.
public static void printPowerOfTwoStars(int n){
if(n <= 0){
System.out.print("*");
}
else{
printPowerOfTwoStars(n-1);
printPowerOfTwoStars(n-1);
}
}

Strange behavior in recursive algorithm,

I was writing a recursive algorithm to calculate Fibonacci numbers in Java as part of a programming 101 course. This is the code:
public class Fib {
public static void main(String[] args) {
Fib fib = new Fib();
}
public Fib() {
int end = 9;
long[] nums = new long[2];
printFib(0, end, nums);
}
private void printFib(int i, int end, long[] nums) {
while(i < end) {
if(i == 0 || i == 1) {
nums[i] = 1;
System.out.println("1");
} else {
long fib;
fib = 0;
fib += (nums[0] + nums[1]);
nums[0] = nums[1];
nums[1] = fib;
System.out.println(fib);
}
i++;
printFib(i, end, nums);
}
}
}
As I was stepping through the program it was working as intended until i became equal to end, the variable telling the printFib method how many Fibonacci numbers it should print out. When ì was equal to end while(i < 1) returns false as expected and the program go to the last }, now you'd(me)
expect the program to return the constructor from which I initially called the function and the program should exit, this not the case. The program goes back to the while statement and somehow evaluates to false again. Then it does the same thing again except the second time it decreases i by 1(what?!) and then proceeds to the else clause when it reaches the if statement. It then does the same thing over and over alternating the amount it subtracts from i between 1 and 2. I've asked my teacher about this and he was unable to explain it.
The program works fully like I intended if I replace the while with an if so maybe there is something about while that I don't know.
Edit
So I realize now that each time the method is called i has a different value which is stored and when the method exits and i = end the program goes back to the previous calls where i had a different value.
You implemented an iterative algorithm to calculate Fibonacci series. That's what the while loop does. There is no point in making the recursive call - printFib(i, end, nums) - at the end.
If you intended a recursive implementation, the entire while loop is not needed.
This code doesn't look right to me.
I would recommend that you not print from your method. Return a value to the main and let it print.
Your recursive method should not have a while loop in it. That's iteration - exactly what you're trying to avoid here.
Your method should have a stopping condition and a call to itself. That's not what you're doing.
Think about it like this:
/**
* Recursive Fibonnaci
* User: mduffy
* Date: 2/11/2015
* Time: 8:50 AM
* #link http://stackoverflow.com/questions/28455798/strange-behavior-in-recursive-algorithm/28455863#28455863
*/
public class Math {
private static Map<Integer, Integer> memo = new ConcurrentHashMap<Integer, Integer>();
public static void main(String [] args) {
for (String arg : args) {
int n = Integer.valueOf(arg);
System.out.println(String.format("n: %d fib(n): %d", n, fibonnaci(n)));
}
}
public static int fibonnaci(int n) {
if (n < 0) throw new IllegalArgumentException("index cannot be negative");
int value = 0;
if (memo.containsKey(n)) {
value = memo.get(n);
} else {
if (n <= 1) {
value = n;
} else {
value = fibonnaci(n-1)+fibonnaci(n-2);
}
memo.put(n, value);
}
return value;
}
}
Basicly this is happening because i would guess that you are thinking of i as an reference which will influence the basic callings of the Fibunacci method calling the sub Fibunacci method. This will finally lead way to many calls of the fibunacci method.
in my eyes the loop doesn´t make sense in your recursive way of solving it.

Java Recursion printing asterisks from one method call

I have an assignment introducing Recursion in Java and I am running into a roadblock. The assignment requires a recursion method to output a number of lines of a number of asterisks depending on the integer value passed to it. For example, if 4 is passed in as variable n, the output would have a first line of one asterisk, next line 2 asterisks, next 3 asterisks, next 4, then 4, 3, 2, & 1 going down.
I have been able to complete the first half of the output (not sure if it is optimal though), but have no clue how to get the method to reverse back down. This is all to be done in one method call with a variable (n) passed to the method.
Here is the method I have so far:
public static void myMethod(int n)
{
if (n <= 1) {
System.out.print("*");
} else {
myMethod(n - 1);
for (int i = 0; i < n; i++) {
System.out.print("*");
}
}
System.out.print("\n"); // new line
}
It is called from main with this:
myMethod(n);
So what I have is a for loop that will print an asterisk on the same line 'n' times. After the for loop it proceeds to the next line and cycles, changing n. But I have no idea how to get it to reverse.
My method prints from the method. My instructor showed me a sample version passing 2 variables (n) and a null string.
public static String myMethod(int n, String displayStr) {
String currentStr = "";
for (int i = 0; i < n; i++)
currentStr += "*";
currentStr += "\n";
if (displayStr == null){
return myMethod((n - 1), currentStr);
} // end base case
else if (n > 0){
return myMethod((n - 1), (currentStr + displayStr + currentStr));
}
else {
return displayStr;
}
} // end recursion method myMethod
His version prints from main using the following code line:
System.out.println(myMethod(n, null));
I have tried his version and it prints the triangle on it's side but the largest line only prints once instead of twice. I have spent all day trying to alter his to add in a duplicate line in the middle and am starting to think it isn't possible.
Any help would be GREATLY appreciated. I am at a complete standstill with this.
Change the method signature to public static void myMethod(int n, boolean reversed) where reversed is initialized to false but flips to true when you print n asterisks. Inside the method, reverse your logic if reversed is true.
You basically just need to print out the current row, then do the recursive call, then print the row again. That way, you get the stack buildup on the way up, and then again on the way down.
Here is an example that uses 2 parameters, one being the max length and the other being the iterator for the recursion.
// bootstrap method to start the recursion
public static void myMethod(int length)
{
myMethod(length, length);
}
public static void myMethod(int length, int i)
{
if (i > 0)
{
int rowLength = length - i + 1;
printRow(rowLength, '*');
myMethod(length, i - 1);
printRow(rowLength, '*');
}
}
public static void printRow(int length, char symbol)
{
for (int i = 0; i < length; i++)
System.out.print(symbol);
System.out.println();
}
Because the output counts up (not *down to zero), you must pass in the number of asterisks to print and the maximum number, so the terminating condition can be established.
Further, the pseudo code for your method is:
if n > max return (terminating condition)
print n asterisks
recursively call with n + 1
print n asterisks
A great deal of code simplification can be achieved if you pass in not the current length to print, but the String of asterisks, so your (private) recursive method could be simply:
private static void myMethod(int n, String s) {
if (s.length() < n) return;
System.out.println(s);
myMethod(n, s + "*");
System.out.println(s);
}
And your public method, which sets up the initial conditions, is then:
public static void myMethod(int n) {
myMethod(n, "*");
}
IMHO an elegant implementation with good code density.

recursion cannot get this right

We have triangle made of blocks. The topmost row has 1 block, the next row down has 2 blocks, the next row has 3 blocks, and so on. Compute recursively (no loops or multiplication) the total number of blocks in such a triangle with the given number of rows.
triangle(0) → 0
triangle(1) → 1
triangle(2) → 3
This is my code:
public int triangle(int rows) {
int n = 0;
if (rows == 0) {
return n;
} else {
n = n + rows;
triangle(rows - 1);
}
}
When writing a simple recursive function, it helps to split it into the "base case" (when you stop) and the case when you recurse. Both cases need to return something, but the recursive case is going to call the function again at some point.
public int triangle(int row) {
if (row == 0) {
return 0;
} else {
return row + triangle(row - 1);
}
}
If you look further into recursive definitions, you will find the idea of "tail recursion", which is usually best as it allows certain compiler optimisations that won't overflow the stack. My code example, while simple and correct, is not tail recursive.
You are not making use of the return value of your function. Instead you always declare a new local variable. Otherwise your solution is quite close to the correct one. Also you should add another return in case you are not at row 0.
public static int triangle (int rows) {
int n = 0;
if (rows == 0) {
return n;
} else {
n = n + rows;
n = n + triangle(rows - 1);
}
return n;
}

Categories