-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path028.go
111 lines (93 loc) · 2.09 KB
/
028.go
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"fmt"
"math"
)
const SIZE int = 1001
// there is a much nicer way of doing this, by understanding that there are
// n/2+1 rings
//
// with the 5x5 spiral:
//
// r0 = 1
//
// r1 = 7 8 9
// 6 2
// 5 4 3
//
// r2 = 21 22 23 24 25
// 20 10
// 19 11
// 18 12
// 17 16 15 14 13
//
// but the brute-force solution was good enough
func calculateSum() int {
var r [SIZE][SIZE]int
// start at the rightmost corner and move inwards
x, y, s := SIZE-1, 0, 0
d := "left"
for i := 0; i < len(r); i++ {
for j := 0; j < len(r[i]); j++ {
r[i][j] = 0;
}
}
N: for n := SIZE*SIZE; n >= 1; n-- {
r[y][x] = n
// are we on a diagonal?
if x == y || int(math.Abs(float64(x-(SIZE-1)))) == y {
s += n
}
// find next coordinates
// can we continue to go left
if d == "left" && x > 0 && r[y][x-1] == 0 {
x--
continue N
}
// can we continue to go down
if d == "down" && y < SIZE-1 && r[y+1][x] == 0 {
y++
continue N
}
// can we continue to go right
if d == "right" && x < SIZE-1 && r[y][x+1] == 0 {
x++
continue N
}
// can we continue to go up
if d == "up" && y > 0 && r[y-1][x] == 0 {
y--
continue N
}
// can we go left
if x > 0 && r[y][x-1] == 0 {
d = "left"
x--
continue N
}
// can we go down
if y < SIZE-1 && r[y+1][x] == 0 {
d = "down"
y++
continue N
}
// can we go right
if x < SIZE-1 && r[y][x+1] == 0 {
d = "right"
x++
continue N
}
// can we go up
if y > 0 && r[y-1][x] == 0 {
d = "up"
y--
continue N
}
}
// fmt.Printf("%v\n", r)
return s
}
func main() {
s := calculateSum()
fmt.Printf("%d\n", s)
}