简体   繁体   中英

Reversing a nested loop

I am trying to reverse this code so that I can print a diamond shape with a border around it. What is the best way to begin reversing a nested loop/series of loops? I tried tinkering around with the code but everything comes out jumbled and out of order. Any advice?

Also, is there a way to make an even number of .'s on each side of the stars at the top? The only way I have been able to make it work prints an even amount on each side by one...

Here is what should be printed to the console: http://i.imgur.com/h55r2.jpg

Here is my code:

public class SixTester {

    public static void main(String[] args)
    {
            int i,j,k;
            int numOfRows = 8;  // Made this a variable, so that the program can make any size diamond (try playing around with different values eg. 2 or 16)

            // Step 1. The first Dash
            for(i=0;i<numOfRows*2 +2;i++)
                    System.out.print(" "); // Number of spaces is double the number of rows in your 'Half Pyramid'
            System.out.println("-");

            // Step 2. The First half diamond
            for (j=0; j<numOfRows ; j++ )
            {
                    for(k=numOfRows*2; k>1+j*2; k--)
                            System.out.print(" ");

                    System.out.print("_/");
                    for (i=0; i< 2+j*4; i++)
                    {
                            // Prepare the Star rectangle, Note that it starts half the way (rows/2)
                            if(j >= numOfRows/2 && (i>j*2- numOfRows/2 && i<j*2+ numOfRows/2)) {
                                    System.out.print("*");                                 
                            }
                            else
                                    System.out.print(".");
                    }
                    System.out.println("\\_");
            }
            // Next Step  - Make the bottom pyramid...but how to reverse?
    }
}

This isn't the most elegant way, but it works. Insert these lines where your code says "but how to reverse?" I've marked off the changes to your code with comments

        // COUNT BACKWARDS NOW. YOU WANT LARGEST ROW FIRST, OTHERWISE IT'S OK EXCEPT...
        for (j=numOfRows-1; j>=0 ; j-- ) 
        {
                for(k=numOfRows*2; k>1+j*2; k--)
                        System.out.print(" ");

                System.out.print("\\_"); // BORDERS ARE BACKWARDS. PUT BORDER ON OTHER SIDE
                for (i=0; i< 2+j*4; i++)
                {
                        if(j >= numOfRows/2 && (i>j*2- numOfRows/2 && i<j*2+ numOfRows/2)) {
                                System.out.print("*");                                 
                        }
                        else
                                System.out.print(".");
                }
                System.out.println("_/"); // PUT BORDER ON OTHER SIDE
        }

        for(i=0;i<numOfRows*2 +2;i++)
                System.out.print(" ");
        System.out.println("-");

If you wrote a builder like this...

public static interface Reflection {
    String reflect(String str);
}

public static class Builder {
    private List<String> lines = new ArrayList<String>();
    private StringBuilder builder = new StringBuilder();
    public void newLine() {
        lines.add(builder.toString());
        builder = new StringBuilder();
    }
    public void repeat(String section, int count) {
        for (int i = 0; i < count; i++) {
            builder.append(section);
        }
    }
    public void padLeft(String section, int count) {
        while (builder.length() < count) {
            builder.append(section, 0, section.length());
        }
    }
    public void reflectX(Reflection reflection) {
        List<String> reflected = new ArrayList<String>();
        for (String line : lines) {
            StringBuilder tmp = new StringBuilder();
            tmp.append(reflection.reflect(line));
            tmp.reverse();
            tmp.append(line);
            reflected.add(tmp.toString());
        }
        lines = reflected;
    }
    public void reflectY(Reflection reflect) {
        List<String> reflection = new ArrayList<String>();
        for (String line : lines) {
            reflection.add(reflect.reflect(line));
        }
        Collections.reverse(reflection);
        lines.addAll(reflection);
    }
    public String build() {
        StringBuilder tmp = new StringBuilder();
        for (String line : lines) {
            tmp.append(line);
            tmp.append('\n');
        }
        return tmp.toString();
    }
    public void write(String string) {
        builder.append(string);
    }
}

Then your code code be simplified to this, but that would just be over engineering:

int nRows = 8;
int pad = 20;
Builder builder = new Builder();

builder.write("_");
builder.padLeft(" ", pad);
builder.newLine();

for (int i = 0; i < nRows; i++) {
    int dots = i * 2 + 1;
    int stars = i >= 4 ? 4 : 0;
    builder.repeat("*", stars);
    builder.repeat(".", dots - stars);
    builder.write("\\");
    if (i < nRows - 1) {
        builder.write("_");
    }
    builder.padLeft(" ", pad);
    builder.newLine();
}
builder.reflectX(new Reflection() {
    @Override
    public String reflect(String str) {
        return str.replace('\\', '/');
    }
});
builder.reflectY(new Reflection() {
    @Override
    public String reflect(String str) {
        return str.replace("\\", "%x").replace("/", "\\").replace("%x", "/").
                replace("_\\", "%x").replace("/_", "_/").replace("%x", "\\_");
    }
});
System.out.println(builder.build());

Result

               __                   
             _/..\_                 
           _/......\_               
         _/..........\_             
       _/..............\_           
     _/.....********.....\_         
   _/.......********.......\_       
 _/.........********.........\_     
/...........********...........\    
\...........********.........../    
 \_.........********........._/     
   \_.......********......._/       
     \_.....********....._/         
       \_.............._/           
         \_.........._/             
           \_......_/               
             \_.._/                 
               __                   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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