Last active
August 29, 2015 14:06
-
-
Save angch/1c30b8128b9d1a233276 to your computer and use it in GitHub Desktop.
https://www.facebook.com/kagesenshi/posts/10152687038904133?comment_id=10152687210704133 and https://www.facebook.com/groups/python.malaysia/permalink/10152645374976380/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
func main() { | |
var n, max_x, max_y, x, y, xdir, ydir int | |
max_x, max_y = 5, 5 | |
var matrix = make([][]int, max_y) | |
P: | |
matrix[n] = make([]int, max_x) | |
n++ | |
if n < max_y { | |
goto P | |
} | |
xdir, n = 1, 0 | |
goto spiral | |
done: | |
fmt.Printf("%2d ", matrix[y][x]) | |
x++ | |
if x >= max_x { | |
x, y = 0, y+1 | |
fmt.Println() | |
if y >= max_y { | |
return | |
} | |
} | |
goto done | |
spiral: | |
n++ | |
matrix[y][x] = n | |
tries := 0 | |
tryagain: | |
x, y = x+xdir, y+ydir | |
if x < 0 || x >= max_x || y < 0 || y >= max_y || matrix[y][x] > 0 { | |
if tries > 0 { | |
x, y = 0, 0 | |
goto done | |
} | |
tries++ | |
x, y = x-xdir, y-ydir | |
xdir, ydir = -ydir, xdir | |
goto tryagain | |
} | |
goto spiral | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def spiral(max_x, max_y): | |
matrix = [] | |
for i in range(0, max_y): | |
matrix.append([0] * max_x) | |
x, y, n, xdir, ydir = 0, 0, 0, 1, 0 | |
while 1: | |
n, tries, matrix[y][x] = n + 1, 6, n + 1 | |
while 1: | |
x, y, tries = x + xdir, y + ydir, tries - 1 | |
if (x < 0 or x >= max_x or y < 0 or y >= max_y or matrix[y][x] > 0): | |
if tries == 0: break | |
x, y = x - xdir, y - ydir | |
xdir, ydir = -ydir, xdir | |
else: break | |
if tries == 0: break | |
for i in matrix: | |
for j in i: | |
print '{0:2}'.format(j), | |
spiral(5, 5) |
cybus:spiral angch$ python spaghetti_spiral.py
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cybus:spiral angch$ go run spaghetti_spiral.go
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9