//package javaapplication1;
/**
Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of the numbers on the diagonals is 101.
What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral formed in the same way?
*/
/**
* this is what one can write with poor tools
*/
/**
* Timing: 1:01 am to 1:54 am
* @author umang
*/
public class Problem28 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int max = 1001;
int arr[][] = new int[max][max];
int x = max / 2;
int y = max / 2;
int count = 0;
int increment = 2;
// initialize first square
arr[x][y] = count++;
arr[x][y++] = count++;
arr[x++][y] = count++;
arr[x][y--] = count++;
arr[x][y--] = count++;
arr[x--][y] = count++;
arr[x--][y] = count++;
arr[x][y++] = count++;
//arr[x][y++] = count++;
//arr[x][y++] = count++;
// y++;
//System.out.println(x + " " + y + " " + count + " " + increment);
while (x != 0 && y != 1) {
increment++;
// System.out.println("start " + x + " " + y + " " + count + " " + increment);
for (int i = 0; i < increment; i++) {
arr[x][y++] = count++;
//y++;
}
y--;
x++;
//System.out.println(x + " " + y + " " + count + " " + increment);
for (int i = 0; i < increment; i++) {
arr[x++][y] = count++;
// System.out.println(x + " " + y + " " + count + " " + increment);
}
x--;
y--;
increment++;
//System.out.println(x + " " + y + " " + count + " " + increment);
for (int i = 0; i < increment; i++) {
arr[x][y--] = count++;
}
x--;
y++;
///System.out.println(x + " " + y + " " + count + " " + increment);
for (int i = 0; i < increment; i++) {
arr[x--][y] = count++;
}
x++;
y++;
//System.out.println("end" + x + " " + y + " " + count + " " + increment);
}
for (int i = 0; i < increment; i++) {
arr[x][y++] = count++;
}
/* for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.printf("%2d ", arr[i][j]);
}
System.out.println("");
}*/
int sum = 0;
for (int i = 0; i < arr.length; i++) {
// System.out.println(arr[i][i] + " ");
sum += arr[i][i];
}
int row = 0;
for (int i = arr.length - 1; i >= 0 && row < arr.length; i--, row++) {
if (row != i) {
sum += arr[row][i];
}
}
System.out.println("sum is " + sum);
}
}
|
No comments:
Post a Comment