summaryrefslogtreecommitdiffstats
path: root/Java/MagicSquare/MagicSquare.java
blob: 934ade563e5b3958828eb9690b9894f6e0fcda34 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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;
	}
}

}
}