Create a gist now

Instantly share code, notes, and snippets.

@angch /spiral.go
Last active Aug 29, 2015

What would you like to do?
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