Last active
May 28, 2019 03:58
-
-
Save louisswarren/f8ae1c593a14bf0b57322d57e66bd4d2 to your computer and use it in GitHub Desktop.
Simulate possums meeting on random walks in python
This file contains hidden or 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
import random | |
class Point: | |
def __init__(self, x, y): | |
self.x = x | |
self.y = y | |
def __add__(self, other): | |
return Point(self.x + other.x, self.y + other.y) | |
def __neg__(self): | |
return Point(-self.x, -self.y) | |
def __sub__(self, other): | |
return self + (-other) | |
def __repr__(self): | |
return f"Point({self.x}, {self.y})" | |
def __eq__(self, other): | |
return (self.x, self.y) == (other.x, other.y) | |
cardinals = Point(0, 1), Point(1, 0), Point(0, -1), Point(-1, 0) | |
class Possum: | |
def __init__(self, start, prob): | |
self.pos = start | |
self.prob = prob | |
def step(self): | |
if random.random() < self.prob: | |
self.pos += random.choice(cardinals) | |
def __repr__(self): | |
return f"Possum({self.pos}, {self.prob})" | |
def diff(self, other): | |
return self.pos - other.pos | |
def walk(self): | |
while True: | |
yield self.pos | |
self.step() | |
def track_collision(n, wp, wq): | |
p_pos = next(wp) | |
q_pos = next(wq) | |
i = 0 | |
yield i | |
while p_pos != q_pos: | |
p_pos = next(wp) | |
q_pos = next(wq) | |
i += 1 | |
yield i | |
print(f"{n}:\t Collided at {p_pos}\t after {i}\t steps!") | |
def do_pair(n): | |
p = Possum(Point(0, 0), 0.8) | |
q = Possum(Point(0, 10), 0.5) | |
yield from track_collision(n, p.walk(), q.walk()) | |
yield None | |
if __name__ == '__main__': | |
pairs = [] | |
n = 0 | |
while True: | |
new_pairs = [] | |
for pair in pairs: | |
if next(pair) is not None: | |
new_pairs.append(pair) | |
new_pairs.append(do_pair(n)) | |
pairs = new_pairs | |
n += 1 | |
#print(len(new_pairs), "still running.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment