Skip to content

Instantly share code, notes, and snippets.

@bgnori
Created February 23, 2014 16:48
Show Gist options
  • Save bgnori/9173846 to your computer and use it in GitHub Desktop.
Save bgnori/9173846 to your computer and use it in GitHub Desktop.
素数ゼミのシミュレーション. 同じ年に羽化した個体がランダムに2匹組み合わさって2匹の子供を残す. ある年に生まれる子孫は同じ年数幼生で過ごす様にはなるが、1つの種類しか生き残らない
#!/usr/bin/python
import heapq
from random import randint, shuffle
import sys
import os
def crossbreed(c, d, n):
"cicada"
for i in range(n):
if c < d:
yield randint(c, d)
elif c == d:
yield c
elif d < c:
yield randint(d, c)
def randpop2(xs):
shuffle(xs)
while len(xs) > 1:
a = xs.pop()
b = xs.pop()
yield a, b
class World:
def __init__(self):
self.cicadas = {}
self.year = 0
for c in crossbreed(2, 30, 100):
self.add(c, c)
def report(self):
xs = self.cicadas.items()
sorted(xs, key=lambda x:x[0])
for y, cicada in xs:
print y, cicada
def add(self, y, c):
xs = self.cicadas.get(y, None)
if xs is None:
xs = []
xs.append(c)
self.cicadas[y] = xs
def do_year(self):
wakeup = self.cicadas.get(self.year, None)
if wakeup is None:
return
del self.cicadas[self.year]
for a, b in randpop2(wakeup):
for c in crossbreed(a, b, 2):
self.add(self.year + c, c)
def run(self, until):
while self.year < until:
self.do_year()
self.year += 1
w = World()
w.run(100)
w.report()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment