-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
55 lines (47 loc) · 784 Bytes
/
main.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
package main
import "fmt"
func spiral(n int) []int {
left, top, right, bottom := 0, 0, n-1, n-1
sz := n * n
s := make([]int, sz)
i := 0
for left < right {
// work right, along top
for c := left; c <= right; c++ {
s[top*n+c] = i
i++
}
top++
// work down right side
for r := top; r <= bottom; r++ {
s[r*n+right] = i
i++
}
right--
// work left, along bottom
for c := right; c >= left; c-- {
s[bottom*n+c] = i
i++
}
bottom--
//work up left side
for r := bottom; r >= top; r-- {
s[r*n+left] = i
i++
}
left++
}
// center (last) element
s[top*n+left] = i
return s
}
func main() {
num := 5
len := 2
for i, draw := range spiral(num) {
fmt.Printf("%*d ", len, draw)
if i%num == num-1 {
fmt.Println("")
}
}
}