繁体   English   中英

在递归中制作钻石

[英]Making a diamond in recursion

//Making a diamond using recursive methods. The diamond is filled with //whitespace then outlined using / and \.


    //Using java, and has to be using recursive methods.

public static void diaTop(int w){ //this is to make top of diamond
        if(w == 0 )return;
        else System.out.print('/'); //printing left side of diamond
        for(int i = 0; i < w; i++){ //for loop to make spaces
            System.out.print(" ");
        }
            System.out.print('\\'); //printing right side of diamond
            System.out.println();
             diaBot(w-1);
        }

//很难转动顶部,所以它开始变小然后放大。

    public static void diaBot(int w){ //this is to make bottom of diamond
        if(w == 0 )return;
        else System.out.print('\\');//printing left side of diamond
        for(int i = 0; i < w; i++){ //for loop to make spaces
            System.out.print(" ");
        }
            System.out.print('/'); //printing right side of diamond
            System.out.println();
             diaBot(w-1);
        }


    public static void main(String[] args) {
        Scanner scnr = new Scanner(System.in);
        System.out.println("Input width of diamond: ");
        int w = scnr.nextInt(); //getting width of diamond.
        diaTop(w);
        diaBot(w);
    }

/* 输出
/ \\ \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / \\ / */

我制定了一个自上而下的解决方案,不是最花哨的部分,但它进行递归调用,任何教授都希望看到它。 我最好在周六晚上上交。 这颗钻石看起来确实有点难看,嗯,但你可以随时按照你喜欢的方式修剪它......

class Diamond {

void draw(int width, int height) {
    if (height - width == height) {
        return;

    } else {
        width -= 2;
        //this bit right here works out the width of spaces
        System.out.print("\n\\");
        for (int i = 0; i < width; i++)
            System.out.print(" ");
        System.out.print("/");

        //This calls the whole thing again, right recursion.
        draw(width, height);
    }
}

void drawTop(int width, int height) {
    if (height - width == height) {
        return;
    } else {

        width -= 2;
       //This does the same as above but in reverse...
        System.out.print("\n/");
        for (int i = 0; i <(height - 2) - width ; i++)
            System.out.print(" ");
        System.out.print("\\");

        //The bit is called here, resursion...
        drawTop(width, height);

    }
}
}

public class Main {

public static void main(String[] args) {

    Diamond diamond = new Diamond();

    //Its not too fancy here, but its right recursion.
    //Go ahead, an add your scanner ere if ya like...
    diamond.drawTop(8,8);
    diamond.draw(8, 8);

}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM