2

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: https://i.stack.imgur.com/SyYzp.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?
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
dustdustdust
  • 55
  • 1
  • 3
  • 7
  • 1
    +1 for taking photo of ascii art – Adam Nov 20 '12 at 01:55
  • I would prefer to have one method for every *heavy* action. By heavy action, I mean every `for-loop` that contains a logic code. Once you have designed these methods, it would be easier to *reverse* the current code. Otherwise, you should just copy and adapt the current code to have a reverse print behavior. – Luiggi Mendoza Nov 20 '12 at 02:03

2 Answers2

2

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("-");
durron597
  • 31,968
  • 17
  • 99
  • 158
  • I was looking moreso for some tips for doing this myself, but I guess it was rather vague to begin with. Thanks for the answer! The only one issue I'm seeing: I want the rectangle of stars in the center to be 8x8 and I need to change the amount of .'s in the bottom pyramid to match [this](http://i.imgur.com/h55r2.jpg). Thank you very much though, +1! – dustdustdust Nov 20 '12 at 02:26
  • 2
    Well, I'm glad my solution isn't perfect then, hopefully this gives you some tips in the right direction. Remember programming is about building big jobs from little jobs, if you correctly analyze the little jobs fixing big bugs should be a lot easier. – durron597 Nov 20 '12 at 02:38
0

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

               __                   
             _/..\_                 
           _/......\_               
         _/..........\_             
       _/..............\_           
     _/.....********.....\_         
   _/.......********.......\_       
 _/.........********.........\_     
/...........********...........\    
\...........********.........../    
 \_.........********........._/     
   \_.......********......._/       
     \_.....********....._/         
       \_.............._/           
         \_.........._/             
           \_......_/               
             \_.._/                 
               __                   
Adam
  • 35,919
  • 9
  • 100
  • 137