Skip to content

Instantly share code, notes, and snippets.

@angch
Last active August 29, 2015 14:06
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 angch/9b2efc8bcc8eefccde13 to your computer and use it in GitHub Desktop.
Save angch/9b2efc8bcc8eefccde13 to your computer and use it in GitHub Desktop.
package main
import "fmt"
func spiral(max_x int, max_y int) {
var n, x, y, xdir, ydir int
xdir = 1
var matrix = make([][]int, max_y)
for i := range matrix {
matrix[i] = make([]int, max_x)
}
for {
n++
matrix[y][x] = n
x, y = x+xdir, y+ydir
if x < 0 || x >= max_x || y < 0 || y >= max_y || matrix[y][x] > 0 {
x, y = x-xdir, y-ydir
xdir, ydir = -ydir, xdir
x, y = x+xdir, y+ydir
if matrix[y][x] != 0 {
break
}
}
}
for y = range matrix {
for x = range matrix[y] {
fmt.Printf("%2d ", matrix[y][x])
}
fmt.Println()
}
}
func main() {
spiral(5, 5)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment