开发者

Create a triangle out of stars using only recursion

I need to to write a method that is called like printTriangle(5);. We need to create an iterative method and a recursive method (without ANY iteration). The output needs to look like this:

*
**
***
****
*****

This code works with the iterative but I can't adapt it to be recursive.

public void printTriangle (int count) {
    int line = 1;
    while(line <= count) {
        for(int x = 1; x <= line; x++) {
            System.out开发者_StackOverflow中文版.print("*");
        }
        System.out.print("\n");
        line++;
    }
}

I should note that you cannot use any class level variables or any external methods.


Notice in your iterative approach that you have two counters: the first is what line you are on line, and the second is what position on the line you are on x. You could create a recursive function that takes two parameters and uses them as nested counters, y and x. Where you decrement x until it reaches 0, then decrement y and set x = y, until both x and y are 0.

You could also notice that each successive line in the triangle is the previous line plus one star. If your recursive function returns a string of stars for the previous line, the next line is always that string plus one more star. So, your code would be something like:

public String printTriangle (int count) {
    if( count <= 0 ) return "";

    String p = printTriangle(count - 1);
    p = p + "*";
    System.out.println(p);

    return p;
 }


Example in python (just for the sake of prototyping, but I hope the idea gets through):

#!/usr/bin/env python

def printTriangle(n):
    if n > 1:
        printTriangle(n - 1)
    # now that we reached 1, we can start printing out the stars 
    # as we climb out the stack ...
    print '*' * n

if __name__ == '__main__':
    printTriangle(5)

Output looks like this:

$ python 2717111.py
*
**
***
****
*****


You can convert a loop to a recursive function like this:

void printStars(int count) {
    if (count == 0) return;

    System.out.print("*");
    printStars(count - 1);
}
printStars(5);    //Prints 5 stars

You should be able to make a similar function to print lines.


You can also do it with a single (not so elegant) recursion,as follows:

public static void printTriangle (int leftInLine, int currLineSize, int leftLinesCount) {
    if (leftLinesCount == 0)
        return;
    if (leftInLine == 0){ //Completed current line?
        System.out.println();
        printTriangle(currLineSize+1, currLineSize+1, leftLinesCount-1);
    }else{
        System.out.print("*");
        printTriangle(leftInLine-1,currLineSize,leftLinesCount);
    }
}

public static void printTriangle(int size){
    printTriangle(1, 1, size);
}

The idea is that the method params represent the complete drawing state.

Note that size must be greater than 0.


You can do it like this:

The method gets the number of stars as a parameter. Let's call it n.

Then it:

  1. calls itself recursively with n-1.

  2. prints a line with n stars.

Make sure to do nothing if n == 0.


#include<iostream>
using namespace std;
 void ll__(int x){
  char static c = '0'; // character c will determine when to put newline
  if(!x){
    if(c=='1'){
      cout<<'\n';
    }
    return;
  }
  if(c=='0'){
    ll__(x-1); //  rows to be called in the stack and differentiated by character '0'
  }
  if(x==1 && c=='0'){
   cout<<'*';
  }else{  // columns to be printed in every row as per the row number in the stack
   c = '1';
   ll__(x-1);
   cout<< '*';
  }
}

int main(){
//writes code here
 ll__(5);
 exit(0);
}


I think this should work... untested off the top of my head.

public void printTriangle(int count)
{    
    if (count == 0) return;
    printTriangle(count - 1);
    for (int x = 1; x <= count; x++) { 
        System.out.print("*"); 
    }
    System.out.print("\n"); 
}


So, you need to create a small block. What information does that block need? Just the maximum. But the recursion needs to know what line its on... you end up with a constructor like:

public void printTriangle (int current, int max)

Now, use that to put the rest of the recursion together:

public void printTriangle (int current, int max)
{ 
    if (current <= max) 
    { 
         // Draw the line of stars...
         for (int x=0; x<current; x++)
         {
             System.out.print("*")
         }
         // add a newline
         System.out.print("\n"); 

         // Do it again for the next line, but make it 1-bigger
         printTriangle(current + 1, max);
    } 
} 

Now, all you have to do, is initiate it:

printTriangle(1, 5);


package playground.tests;

import junit.framework.TestCase;

public class PrintTriangleTest extends TestCase {
    public void testPrintTriangle() throws Exception {
        assertEquals("*\n**\n***\n****\n*****\n", printTriangleRecursive(5, 0, 0));
    }

    private String printTriangleRecursive(int count, int line, int character) {
        if (line == count)
            return "";
        if (character > line)
            return "\n" + printTriangleRecursive(count, line + 1, 0);
        return "*" + printTriangleRecursive(count, line, character + 1);
    }

}


    void trianglePrint(int rows){
            int static currentRow = 1;
            int static currentStar = 1;

            // enter new line in this condition
            // (star > currentrow)  

            if (currentStar > currentRow ){
                currentStar = 1;
                currentRow++;
                cout << endl;
            }

            if (currentRow > rows){
                return; // finish
            }

            cout << "*";
            currentStar++;

            trianglePrint(rows);
        }


i think this should do it

public void printTriangle (int count) {
   if(count >= 0) {
      printTriangle(count-1);
          for(int i = 0; i < count; i++) {
              System.out.print("*" + " ");
          }
      System.out.println(); 
   }
}


package com. company;

    public class practise7 { 
    static void star1(int n){
            if(n>0){
                for(int i = 0; i<n; i++){
    
                    System.out.print("*");
                }
                System.out.println("");
                star1(n-1);
            }
    
        }
      public static void main(String[] args) {
    star1(4); 
}
}

to forward star pattern

package com. company;
        
        public class practise7 { 
        static void star1(int n){
                if(n>0){
                    star1(n-1);
                    for(int i = 0; i<n; i++){
        
                        System.out.print("*");
                    }
                    System.out.println("");
                    
                }
        
            }
          public static void main(String[] args) {
        star1(4); 
    }
    }


I found that the best way do this was:

    public static void printTriangle(int x) {
        if(x == 0) {
            return;
        }
        printTriangle(x-1);
        printStars(x);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜