Java Simple Recursive Algorithm -


here simple recursion question in java. 1 have been working on need refine approach.

write recursive method 2 int parameters, m , n. precondition requires 0 <= m , m <= n. method prints line of m asterisks, line of m+1 asterisks, , on line of n asterisks. same pattern repeated backward: line of n asterisks, n-1, , on down n. loop allowed in implementation loop print line of m asterisks.

this have far 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)      {         (int = 0; < m; i++)          {            system.out.print("*");         }             system.out.println("");     }     public static void main(string[] args)     {        int m = 3;        int n = 5;         asterisk(m, n);    } } 

think of way: printasterisk(6, 5) prints nothing. printasterisk(3, 5) prints 3 asterisks, inserts printasterisk(4, 5), prints 3 asterisks again.

expected output

printasterisk(3, 5) *** **** ***** ***** **** *** 

my current output

printasterisk(3, 5) *** **** ***** 

it's simpler.

public static void asterisk(int m, int n) {     printasterisk(m);     if (m < n) {         asterisk(m + 1, n);     }     printasterisk(m); } 

just print m asterisk @ begin , end of function. , if m less n recurse m + 1.

in case of preventing 2 printed lines if m > n this:

public static void asterisk(int m, int n) {     if (m <= n) {         printasterisk(m);         asterisk(m + 1, n);         printasterisk(m);     } } 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -