public class MagicSquare
{
public static int[][] grid = new int[3][3];
public static int i = 0;
public static int j = 0;
public static void main(String[] args) {
int x = 1;
int y = 2;
int z = 0;
while(z < 9)
{
int holdx = x;
int holdy = y;
z++;
x++;
y--;
if(x == 3)
{
x = 0;
}
if(y == -1)
{
y = 2;
}
if(y == 3)
{
y = 0;
}
if(grid[x][y] == 0)
{
grid[x][y] = z;
}
else
{
holdy++;
if(holdy == 3)
{
holdy = 0;
}
grid[holdx][holdy] = z;
x = holdx;
y = holdy;
}
}
for(int i = 0; i < 3; i++)
{
System.out.print(grid[i][0]+", ");
}
System.out.println(" ");
for(int i = 0; i < 3; i++)
{
System.out.print(grid[i][1]+", ");
}
System.out.println(" ");
for(int i = 0; i < 3; i++)
{
System.out.print(grid[i][2]+", ");
}
}
THE OUTPUT LOOKS LIKE THIS:
2, 4, 9,
6, 8, 1,
7, 3, 5,
Hello, I wrote a Black Magic code that is able to fill in the grids of the square up and the right of it, but if it is filled with a number then the next number would be put in the square that is below its current spot.
Then, go one square up and to the right and put the next integer there, and if I also go off the grid, then the next number will wrap around to the bottom and/or left. This program run until all the squares are filled.
I was wondering if it is possible to condense my code starting at my while loop to the end of my for loop into a shorter code?
Someone said that I would be able to code this USING JUST 2 lines, and I think that is bizarre... but they said it's doable!
Any hints, help, or pointer would be appreciated!
Thank you so much!