Skip to content

Instantly share code, notes, and snippets.

@cyingfan
Last active August 5, 2016 09:46
Show Gist options
  • Save cyingfan/be709c5edf1aedddfb9043579d159ef3 to your computer and use it in GitHub Desktop.
Save cyingfan/be709c5edf1aedddfb9043579d159ef3 to your computer and use it in GitHub Desktop.
spiraling number in python
class Spiral(object):
def __init__(self, xsize=4, ysize=None):
self.xsize = xsize
self.ysize = xsize if ysize is None else ysize
self.x = 0
self.y = -1
self.vx = 0
self.vy = 1
self.max = self.xsize * self.ysize
self.init_board()
self.num = 1
def init_board(self):
self.board = []
for x in xrange(self.xsize):
self.board.append([])
for y in xrange(self.ysize):
self.board[x].append(0)
def move(self):
next_x = self.x + self.vx
next_y = self.y + self.vy
if next_y < 0 or next_y >= self.ysize or next_x < 0 or next_x >= self.xsize or self.board[next_x][next_y] != 0:
self.vx, self.vy = self.vy, self.vx * -1
self.x = self.x + self.vx
self.y = self.y + self.vy
print 'position:',self.x,self.y,'vector:',self.vx,self.vy
def populate(self):
while (self.num <= self.max):
self.move()
self.board[self.x][self.y] = self.num
self.num += 1
def draw(self):
self.populate()
for x in self.board:
for y in x:
print "{:5}".format(y),
print
Spiral(5,6).draw()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment