summaryrefslogtreecommitdiffstats
path: root/Java/MagicSquare/MagicSquare.java
diff options
context:
space:
mode:
Diffstat (limited to 'Java/MagicSquare/MagicSquare.java')
-rw-r--r--Java/MagicSquare/MagicSquare.java75
1 files changed, 75 insertions, 0 deletions
diff --git a/Java/MagicSquare/MagicSquare.java b/Java/MagicSquare/MagicSquare.java
new file mode 100644
index 0000000..934ade5
--- /dev/null
+++ b/Java/MagicSquare/MagicSquare.java
@@ -0,0 +1,75 @@
+class MagicSquare{
+
+final int maxSize;
+int size;
+int mSquare [][];
+int row, col;
+
+public MagicSquare (int s){
+maxSize = 15;
+if (s > maxSize)
+ size = maxSize;
+else
+ size = s;
+
+mSquare = new int [size][size];
+row = col - 0;
+intSquare();
+}
+
+private void intSquare(){
+int count, mid;
+
+for (row = 0; row<size; row++)
+ for (col = 0; col < size; col++)
+ mSquare [row][col] = 0;
+
+count = 1;
+mid = size/2;
+row = 0;
+col = mid;
+
+while (count <= size * size) {
+ if(mSquare [row][col] != 0)
+ back();
+ mSquare[row][col] = count;
+ count ++;
+ forward();
+}
+}
+
+private void forward(){
+row --;
+col ++;
+check();
+}
+private void back(){
+row++;
+col--;
+check();
+row++;
+check();
+}
+
+private void check(){
+if(row < 0){
+row = size - 1;
+}
+else {
+ if(row ==size){
+ row = 0;
+ }
+}
+if(col < 0){
+col = size - 1;
+}
+else {
+ if(col == size){
+ col=0;
+ }
+}
+
+}
+}
+
+