Skip to content

Instantly share code, notes, and snippets.

@itayB
Created November 4, 2013 10:45
Show Gist options
  • Save itayB/7300906 to your computer and use it in GitHub Desktop.
Save itayB/7300906 to your computer and use it in GitHub Desktop.
public class MagicSquare {
/* fields */
public int square[][];
/* constructor */
public MagicSquare(int size) {
this.square = new int[size][size];
for (int i = 0; i < square.length; i++)
for (int j = 0; j < square.length; j++)
this.square[i][j] = 0;
}
/* public methods */
public void fillSquare() {
int value = 1;
int x = this.square.length / 2;
int y = 0;
while (this.square[x][y] == 0) {
// System.out.println(value);
this.square[x][y] = value;
x = (x + 1) % this.square.length;
y = y == 0 ? this.square.length - 1 : y - 1;
if (this.square[x][y] != 0) {
x = x == 0 ? this.square.length - 1 : x - 1;
y = (y + 2) % this.square.length;
}
value++;
}
}
public String toString() {
String str = "";
for (int i = 0; i < square.length; i++) {
for (int j = 0; j < square.length; j++)
if (square[j][i] < 10)
str += " " + square[j][i];
else
str += " " + square[j][i];
str += "\n";
}
return str;
}
}
public class Main {
public static void main(String args[]) {
MagicSquare square = new MagicSquare(7);
square.fillSquare();
System.out.println(square.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment