import random
from matplotlib.pyplot import show, imshow
#random_fun = lambda: random.gauss(0.5, 0.2)
random_fun = random.random
class T(object):
@staticmethod
def regen(x,y):
return [[(random_fun(), random_fun(), 1.0) for i in xrange(y)] for j in xrange(x)]
@staticmethod
def eachpair(x,y):
for i in xrange(x):
for j in xrange(y):
yield (i,j)
@staticmethod
def diagonally(x,y):
for s in xrange(x+y):
for i in xrange(max(0, s-x), min(s,x)):
yield i, s-i-1
@staticmethod
def iterchange(tab, steps, ev=10):
changes = 0
x = len(tab)
y = len(tab[0])
for s in xrange(steps):
if s%ev==0:
print s,T.measure(tab)
for i,j in T.diagonally(x, y):
if i+1<x and tab[i][j][0] < tab[i+1][j][0]:
tab[i][j], tab[i+1][j] = tab[i+1][j], tab[i][j]
changes+=1
if j+1<y and tab[i][j][1] < tab[i][j+1][1]:
tab[i][j], tab[i][j+1] = tab[i][j+1], tab[i][j]
changes+=1
print s+1, T.measure(tab), changes
@staticmethod
def measure(tab):
count = 0;
x = len(tab)
y = len(tab[0])
for i in xrange(x-1):
for j in xrange(y-1):
if tab[i][j][0] < tab[i+1][j][0]:
count+=1
if tab[i][j][1] < tab[i][j+1][1]:
count+=1
return count
@staticmethod
def display(tab):
imshow(tab)
show()
# usage:
# launch `ipython`
# enter `%run thisfile.py`
# then enter lines below
tab = T.regen(100, 100)
T.iterchange(tab, 1000, 50)
T.display(tab)