首页 > 解决方案 > 递归制作钻石

问题描述

//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);
    }

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

标签: javarecursion

解决方案


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

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);

}
}

推荐阅读