Commits

Janto Dreijer committed 43c6b11

add pypy test

  • Participants
  • Parent commits b2bcd46

Comments (0)

Files changed (1)

+from __future__ import division
+from pprint import pprint
+import time
+import random
+
+colors = range(5)[1:]
+
+def where_eq_set(a, old, new):
+	for row in a:
+		for y in range(len(row)):
+			if row[y] == old:
+				row[y] = new
+
+class Grid(object):
+	def __init__(self, X, Y):
+		self.X = X
+		self.Y = Y
+		self.rows = [[0 for y in range(Y)] for x in range(X)]
+
+	def populate(self):
+		for x in range(self.X):
+			for y in range(self.Y):
+				self.rows[x][y] = random.choice(colors)
+
+	def labels(self):
+		labels = [[0 for y in range(self.Y)] for x in range(self.X)]
+		unused = []
+		counter = 0
+		for x in range(self.X):
+			for y in range(self.Y):
+				c = self.rows[x][y]
+				# check if colors match any visited neighbors
+				connected = False
+				if 1 <= y and c == self.rows[x][y-1]:
+					labels[x][y] = labels[x][y-1] # apply same label
+					connected = True
+				if 1<= x and c == self.rows[x-1][y]:
+					if connected:
+						old_label = labels[x-1][y]
+						where_eq_set(labels, old_label, labels[x][y]) # reset labels
+						unused.append(old_label)
+					else:
+						labels[x][y] = labels[x-1][y] # apply same label
+					connected = True
+
+				if not connected: # unconnected
+					if 1 and unused:
+						label = unused.pop()
+						labels[x][y] = label
+					else:
+						labels[x][y] = counter
+						counter += 1
+		print unused
+		return labels
+
+	def apply_gravity(self):
+		for row in self.rows:
+			for y in range(self.Y):
+				row[y]
+
+	def show(self):
+		print pprint(self.rows)
+
+def main():
+	X = 500
+	Y = 500
+	grid = Grid(X, Y)
+	t = time.time()
+	grid.populate()
+
+	#~ grid.apply_gravity()
+	grid.labels()
+	#~ pprint(grid.labels())
+	print time.time() - t, "sec"
+
+	#~ import pylab
+	#~ import numpy
+	#~ pylab.matshow(numpy.asarray(grid.labels()))
+	#~ pylab.matshow(numpy.asarray(grid.rows))
+	#~ pylab.show()
+
+
+if __name__ == "__main__":
+	main()