Guest User

simulating a bullet problem

a guest
Nov 11th, 2015
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.92 KB | None | 0 0
  1. from collections import namedtuple, Counter
  2. from itertools import permutations
  3. from random import random
  4.  
  5. Bullet = namedtuple("Bullet", ("time", "speed"))
  6.  
  7.  
  8.  
  9. def ctime(bullet1, bullet2):
  10.     """ time bullet1 will collide with bullet2, or None if no collision."""
  11.     # swap bullets so that bullet2 is fired second
  12.     if bullet2.time < bullet1.time: bullet1,bullet2 = bullet2,bullet1
  13.  
  14.     if bullet2.speed <= bullet1.speed: return None
  15.    
  16.     # where is bullet1 when bullet2 is fired?
  17.     b1startPos = (bullet2.time - bullet1.time)*bullet1.speed
  18.     # how long will it take bullet2 to catch up?
  19.     catchUpTime = b1startPos/(bullet2.speed - bullet1.speed)
  20.    
  21.     return catchUpTime + bullet2.time
  22.  
  23. def sim(bullets):
  24.     """Input: list of bullets. Output: list of surviving bullets."""
  25.     while True:
  26.         n = len(bullets)
  27.         ctimes = [ctime(bullets[i],bullets[i+1]) for i in xrange(n-1)]
  28.         collisions = [(i,c) for (i,c) in enumerate(ctimes) if c != None]
  29.         if not collisions: return bullets
  30.         nextCollision = min(collisions, key=lambda (i,c): c)
  31.         indexNextCollision = nextCollision[0]
  32.         bullets = bullets[:indexNextCollision]+bullets[indexNextCollision+2:]
  33.     return bullets
  34.  
  35. def monte(n, trials):
  36.     """ returns number of times (out of trials) that all bullets died."""
  37.     deaths = 0
  38.     for i in xrange(trials):
  39.         bullets = [Bullet(i,random()) for i in xrange(n)]
  40.         if len(sim(bullets)) == 0: deaths += 1
  41.     return deaths
  42.  
  43. def simulatePermutations(n):
  44.     """ returns Counter of how many bullets survived in each of n! trials,
  45.    each trial being one permutation of n randomly chosen speeds. """
  46.     speeds = [random() for i in xrange(n)]
  47.     def results():
  48.         for speedperm in permutations(speeds):
  49.             bullets = [Bullet(i,s) for (i,s) in enumerate(speedperm)]
  50.             yield sim(bullets)
  51.     return Counter(map(len, results()))
Advertisement
Add Comment
Please, Sign In to add comment