Skip to content

Instantly share code, notes, and snippets.

@quantumelixir
Created January 14, 2011 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quantumelixir/780080 to your computer and use it in GitHub Desktop.
Save quantumelixir/780080 to your computer and use it in GitHub Desktop.
Prints a clockwise spiral of numbers 1, 2, 3, ...
package main
import "fmt"
func main() {
size := 7
grid := make([][]int, size)
for k := 0; k < size; k++ {
grid[k] = make([]int, size)
}
mid := (size - 1)/2
grid[mid][mid] = 1
x, y := mid, mid
step, count := 1, 2
dx, dy := 0, 1
for ; count <= size*size; step++ {
for k := 1; count <= size*size && k <= 2; k++ {
for i := 1; count <= size*size && i <= step; i++ {
x+=dx
y+=dy
grid[x][y] = count
count++
}
dx, dy = dy, dx
}
dx, dy = -dx, -dy
}
for i := 0; i < size; i++ {
for j := 0; j < size; j++ {
fmt.Printf("%d\t", grid[i][j])
}
fmt.Printf("\n")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment