Multiple overlapping squares in Java

Viewed 93

How can we make multiple overlapping squares (of different lengths) with the same top left corner using a single method in Java?

For example if the arguments of the function are 5, 7 then the output should look like:

#######
#   # #
#   # #
#   # #
##### #
#     #
#######

If the arguments are 2, 4, 6 then the output should look like:

######
## # #
#  # #
#### #
#    #
######

I am able to draw single squares, and multiple squares separately, but facing problems with this.

Thanks.

1 Answers
  1. Create a 2d boolean array for the largest square.
  2. For each square mark in this array the cells that should be filled.
  3. Print the 2d array.

For the arguments 5 and 7 it would be something like this:

boolean[][] arr = new boolean[7][7];
for(int i = 0; i < 7; i++){
    for(int j = 0; j < 7; j++){
        if(i == 0 || j == 0 || i == 6 || j == 6){
            arr[i][j] = true;
        }
    }
}
for(int i = 0; i < 5; i++){
    for(int j = 0; j < 5; j++){
        if(i == 0 || j == 0 || i == 4 || j == 4){
            arr[i][j] = true;
        }
    }
}
for(int i = 0; i < 7; i++){
    for(int j = 0; j < 7; j++){
        if(arr[i][j]){
            System.out.print("#");
        }
        else{
            System.out.print(" ");
        }
    }
    System.out.println();
}
Related