Java 仅使用递归从星星中创建一个三角形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2717111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a triangle out of stars using only recursion
提问by Alec Gorge
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:
我需要编写一个名为 like 的方法printTriangle(5);
。我们需要创建一个迭代方法和一个递归方法(没有任何迭代)。输出需要如下所示:
*
**
***
****
*****
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.print("*");
}
System.out.print("\n");
line++;
}
}
I should note that you cannot use any class level variables or any external methods.
我应该注意,您不能使用任何类级变量或任何外部方法。
采纳答案by Michael Petito
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.
请注意,在您的迭代方法中,您有两个计数器:第一个是您在哪条线上line
,第二个是您在该线上的哪个位置x
。您可以创建一个递归函数,它接受两个参数并将它们用作嵌套计数器,y
并且x
. 递减 x 直到它达到 0,然后递减 y 并设置 x = y,直到 x 和 y 都为 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;
}
回答by SLaks
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.
您应该能够制作类似的功能来打印线条。
回答by miku
Example in python (just for the sake of prototyping, but I hope the idea gets through):
python中的示例(只是为了原型设计,但我希望这个想法能够通过):
#!/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
*
**
***
****
*****
回答by Eyal Schneider
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.
请注意,大小必须大于 0。
回答by Kelsey
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");
}
回答by Ilya Kogan
You can do it like this:
你可以这样做:
The method gets the number of stars as a parameter. Let's call it n.
该方法获取星数作为参数。我们称之为n。
Then it:
然后它:
calls itself recursively with n-1.
prints a line with n stars.
用 n-1 递归调用自身。
打印一条带有 n 颗星的线。
Make sure to do nothing if n == 0.
如果 n == 0,请确保什么都不做。
回答by Jerry
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);
回答by Carl Manaster
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);
}
}
回答by Fareed Alnamrouti
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);
}
回答by Razakii
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();
}
}