Java Recursion General Concept - java

Here is a simple recursion question in java. This one I have been working on but need to refine my approach.
Write a recursive method with two int parameters, m and n. The precondition requires 0 <= m and m <= n. The method prints a line of m asterisks, then a line of m+1 asterisks, and so on up to a line of n asterisks. Then the same pattern is repeated backward: a line of n asterisks, then n-1, and so on down to n. The only loop allowed in your implementation is a loop to print a line of m asterisks.
This is what I have so far as test methods
package Recursion;
class Asterisk
{
public static void asterisk(int m, int n)
{
if (m == n)
{
printAsterisk(n);
return;
}
else if (m < n)
{
printAsterisk(m);
asterisk(m + 1, n);
}
else
{
printAsterisk(m);
asterisk(m - 1, m);
}
}
public static void printAsterisk(int m)
{
for (int i = 0; i < m; i++)
{
System.out.print("*");
}
System.out.println("");
}
public static void main(String[] args)
{
int m = 3;
int n = 5;
asterisk(m, n);
asterisk(n, m);
}
}

So, you need this:
printAsterisk(3, 5)
***
****
*****
*****
****
***
Think of it this way: printAsterisk(6, 5) prints nothing. printAsterisk(3, 5) prints 3 asterisks, then inserts printAsterisk(4, 5), then prints 3 asterisks again.

The following code will work:
class Test {
public static void asterisk(int m, int n) {
if (m == n) {
printAsterisk(m);
return;
} else if (m < n) {
printAsterisk(m);
asterisk(m + 1, n);
} else {
printAsterisk(m);
asterisk(m - 1, n);
}
}
public static void printAsterisk(int m) {
for (int i = 0; i < m; i++) {
System.out.print("*");
}
System.out.println("");
}
public static void main(String[] args) {
int m = 3;
int n = 5;
asterisk(m, n);
asterisk(n, m);
}
}
Please note that this is not the right way to do it. Since this question feels like an assignment, I will not post the accurate version. Now, your task is to remove two calls in the main method to asterisk and modify the method to work with a single call.

Your approach is fine you just need to think about what's going into printAsterisk(int m, int n).
A recursive function can often be thought of as solving one small part of a repeatable problem and then delegating the rest of the problem to itself using different parameters.
Consider the following output (printAsterisk(4, 4);):
****
If we wanted to get the following output (printAsterisk(3, 4);):
***
****
***
it is easy to see that this output contains the output of printAsterisk(4, 4); in the middle so when you call printAsterisk(3, 4); it should print 3 asterisks, call printAsterisk(4,4); and then print the remaining 3 asterisks.
If you extend this a bit further the implementation should be easy to see.

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: The fatorial doesn't give the right result, but I didn't find errors.

I developed my codes for fatorial in Java, compiling and running in a terminal with BlueJ. I corrected the error, but the fatorial doesn't give the right result. Check the code:
public class Fatorial
{
public static void main (String [] args)
{
int i, fat = 4;
for (i=1;i<fat;i++)
{
fat=fat*i;
}
System.out.print(fat);
}
}
The right reuslt should be fator(4) = 24.
It should be similar to like:
public class Fatorial3 {
public static void main(String[] args) {
int num, fatorial, aux;
num = 4;
aux = num;
fatorial = 1;
while(aux > 1){
fatorial = fatorial * (aux);// Aqui não podemos subtrair 1, porque assim seria o fatorial de num-1 (4).
aux--;
}
System.out.println("O fatorial de "+num+" é: "+fatorial);
}
}
But I want to keep my original codes.
If you unroll the loop structure, this is what you are doing:
int i, fat = 4; // fat is 4
i = 1; // i is 1
fat = fat * i; // fat = 4 * 1 = 4
++i; // i is 2
fat = fat * i; // fat = 4 * 2 = 8
++i; // i is 3
fat = fat * i; // fat = 8 * 3 = 24
++i; // i is 4, and that is less than 24, so keep going...
Eventually, fat overflows, and becomes negative, so the loop will terminate, and fat will be a large negative number.
If you want to keep a similar structure, add another variable to represent the argument of the factorial operator:
int i, n = 4, fat = 1;
for (i=1;i<=n;i++)
{
fat=fat*i;
}
System.out.print(fat);
A non-recursive solution would be to iterate down instead of up:
public static void main(String[] args) {
System.out.print(factorial(4));
}
public static long factorial(long num) {
for (long i = num-1; i > 0; i--)
{
num=num*i;
}
return num;
}
You could use a do...while loop. :)
public static int factorial(int number){
int result= 1;
int currentNumber = number;
do{
result = result * currentNumber;
currentNumber--;
}while (currentNumber > 1);
return result;
}
Then you would just print the returned result...
System.out.println(factorial(4));
You mean factorial? You can do it this way and it's far more easier using recursion
public class Factorial {
public static void main(String[] args) {
System.out.println(fact(4));
}
public static long fact (long n) {
if (n <= 1)
return 1;
else
return n * fact (n-1);
}
}
By the way when you're using for loop, you don't have to declare "i" outside the loop. Declaration is in the loop for (int i = 0; i < fat; i++)
You're reassigning i to be 4 when you declare your for loop. The reason the stated answer uses three variables for the loop is so that we don't multiply by 0 or any negative number.
Another suggestion for me would be to never declare multiple variables on the same line: It makes ones code hard to read and understand at a glance. In this case, both i and fat are being assigned 4 but this is not immediately obvious.
Another problem is that you are checking against fat, which changes with every execution of the loop. You need to be checking against a number which does not change, but fat does.
Try splitting up your variable declaration and reposting what you intend on working, that may help us guide you to where you want to be.

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.

Basic Java Recursion Method

I am having a lot of trouble with this basic recursion problem in java; any pointers would be great.
"Write a static recursive method to print out the nth term of the
geometric sequence: 2, 6, 18, 54."
From what I can gather, somewhere in the code I should be recursively multiplying something by 3, but I'm struggling to figure out how to do this. I know I need a termination statement, but when does that occur? Do I need a helper method?
A Recursive Function is a function whose implementation references itself. Below is some funny example:
public class Inception {
public void dream() {
boolean enoughDreaming = false;
//Some code logic below to check if it's high time to stop dreaming recursively
...
...
if(!enoughDreaming) {
dream(); //Dream inside a Dream
}
}
}
And the solution for your problem:
public class GeometricSequence {
public static void main(String[] args) {
//Below method parameters - 5 = n, 1 = count (counter), res = result (Nth number in the GP.
System.out.println(findNthNumber(5, 1, 2));
}
public static int findNthNumber(int n, int count, int res) {
return ((count == n)) ? res : findNthNumber(n, count+1, res *3);
}
}
EDIT:
The above class uses "int", which is good only for small numbers (because of Integer Overflow problem). The below class is better for all types/numbers:
public class GeometricSequence {
public static void main(String[] args) {
//Below method parameters - 5 = n, 1 = count (counter), res = result (Nth number in the GP.
System.out.println(findNthNumber(2000, 1, new BigInteger("2")));
}
public static BigInteger findNthNumber(int n, int count, BigInteger res) {
return ((count == n)) ? res : findNthNumber(n, count+1, res.multiply(new BigInteger("3")));
}
}
This is the simplest example of recursion.
You need a method declaration.
You need to check if the end has been reached.
Otherwise you need to call the method again with an operation which makes the difference between one term and the next.
Yes, you need a termination condition - basically when you've taken as many steps as you need. So consider how you want to transition from one call to another:
How are you going to propagate the results so far?
What extra state do you need to keep track of how many more steps you need to take?
What are you going to return from the method?
Here's a C# example (I know your doing Java but it's pretty similar)
public static void Recursive(int counter, int iterations, int value, int multiplier)
{
if (counter < iterations)
{
Console.WriteLine(value);
counter++;
Recursive(counter, iterations, (value * multiplier), multiplier);
}
}
So when you run the function you enter the parameters
"counter" will always be 0 when you first call it
"iterations" is the value of n
"value" is your starting value, in your case 2
"multiplier" is how much you want to multiply by each iteration, in your case 3
Every time it runs it will check to see if counter is less than iterations. If it is more, the value is printed, the counter is incremented, the value is multiplied by the multiplier and you add the same parameters back in to the function.
A recursive solution: Seq(1) is the first element of the sequence .... Seq(n-th)
public static void main(String args[]) throws Exception {
int x = Seq(3); //x-> 18
}
public static int Seq(int n){
return SeqRec(n);
}
private static int SeqRec(int n){
if(n == 1)
return 2;
else return SeqRec(n - 1) * 3;
}
Non-Recursive solution:
public static int Non_RecSeq(int n){
int res = 2;
for(int i = 1; i < n; i ++)
res *= 3;
return res;
}
public static void main(String args[]) throws Exception {
int x = Non_RecSeq(3); //x-> 18
}

How can I make a recursive version of my iterative method?

I am trying to write a recursive function in Java that prints the numbers one through n. (n being the parameter that you send the function.) An iterative solution is pretty straightforward:
public static void printNumbers(int n){
for(int i = 1; i <= n; i++){
System.out.println(i);
i++;
}
As a new programmer, I'm having troubles figuring out how a recursive version of this method would work.
You are using a for loop that is iterating from i=1 to n. As you want to do this with recursion and it is easier to pass n instead of i and n, we just reverse the whole thing, so we count down n to 1. To keep the order of the prints, we first call the recursive function and print the number after the execution:
public static void printNumbers ( int n )
{
if ( n > 0 )
{
printNumbers( n - 1 ); // n - 2, if the "i++" within the for loop is intended
System.out.println( n );
}
}
For simple iterative -> recursive conversions it is easy to change loops into a format like this:
public static void printNumbers ( int n )
{
int i = 1;
while ( i <= n )
{
System.out.println( i );
i++; // i += 2, if the "i++" within the for loop is intended
}
}
Now you can easily transform that into a recursive function:
public static void printNumbers ( int n, int i )
{
if ( i <= n )
{
System.out.println( i );
i++; // i += 2, if the "i++" within the for loop is intended
printNumbers( n, i );
}
}
Everything else is optimization.
The recursive version needs two arguments (n and i) so make it an auxiliary non-public method and just call it from the public method to start the recursion going:
static void auxPrintNumbers(int n, int i){
if(i <= n) {
System.out.println(i);
auxPrintNumbers(i + 1);
}
}
public static void printNumbers(int n){
auxPrintNumbers(n, 1);
}
Your iterative version has some problems: you are iterating i twice, in the for statement then again at the end of the loop; also you should let i < n be the ending condition of your loop.
To answer your question, obviously the recursive function will have to print out the current number and if the current number hasn't yet reached n, call itself again - so it must take the current number (which we're calling i in the iterative version) as a parameter - or the class needs to hold it as an instance variable, but I'd stick with the parameter.
According to your function that prints every odd number from 1 to n the recursive function should look something like this:
public static void printNumbersRecursive(int n)
{
if (n % 2 == 0) printNumbersRecursive(n - 1);
else if (n > 0)
printNumbersRecursive(n - 2);
System.out.println(n);
}
if it is an error and that you'd want to print EVERY number from 1 to n then:
public static void printNumbersRecursive(int n)
{
if (n > 0)
printNumbersRecursive(n - 1);
System.out.println(n);
}
A class version (just for fun):
class R {
private final int n;
public R (final int n) {
if (n <= 0) {
throw new IllegalArgumentException("n must be positive");
}
this.n = n;
}
#Override
public String toString () {
final StringBuilder sb = new StringBuilder();
if (this.n > 1) {
sb.append(new R(this.n - 1).toString());
}
sb.append(this.n).append(" ");
return sb.toString();
}
}
Used as:
System.out.println(new R(10));
public static void printNumbers(int n){
if( n > 1 ){
printNumbers(n - 1);
}
System.out.println(n);
}
This function calls itself recursively until it reaches n = 1. From this point all values are printed in correct order: 1, 2, 3, ...

Categories