diff options
author | msglm <msglm@techchud.xyz> | 2023-01-14 05:31:48 -0600 |
---|---|---|
committer | msglm <msglm@techchud.xyz> | 2023-01-14 05:31:48 -0600 |
commit | 9d53d8857eaa1c9405894a88ca75bc4657e42f35 (patch) | |
tree | eb1efc1d028b949dd83bb710c68be8eff58f26e7 /Java/MagicSquare | |
download | school-code-9d53d8857eaa1c9405894a88ca75bc4657e42f35.tar.gz school-code-9d53d8857eaa1c9405894a88ca75bc4657e42f35.tar.bz2 school-code-9d53d8857eaa1c9405894a88ca75bc4657e42f35.zip |
Diffstat (limited to 'Java/MagicSquare')
-rw-r--r-- | Java/MagicSquare/MagicSquare.java | 75 | ||||
-rw-r--r-- | Java/MagicSquare/Main.java | 25 |
2 files changed, 100 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; + } +} + +} +} + + diff --git a/Java/MagicSquare/Main.java b/Java/MagicSquare/Main.java new file mode 100644 index 0000000..6fb1f19 --- /dev/null +++ b/Java/MagicSquare/Main.java @@ -0,0 +1,25 @@ +import java.util.Scanner; + +class Main{ + public static void main(String[] args) { + Scanner sc = new Scanner (System.in); + System.out.println("enter size of square, must be odd"); + + int size = sc.nextInt(); + + while(size % 2 == 0){ + System.out.println("not odd"); + size = sc.nextInt(); + } + + MagicSquare mSquare = new MagicSquare(size); + + int[][] sq = mSquare.mSquare; + for (int i = 0; i < sq.length; i++){ + for(int j = 0; j < sq[i].length; j++){ + System.out.print(sq[i][j] + " "); + } + System.out.println(); + } + } + } |