Advertisement
Guest User

Untitled

a guest
Jul 27th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.20 KB | None | 0 0
  1. import sys,random
  2.  
  3. def cellular_automaton(num_cells, num_gens, rules):
  4.     """Prints out generations of a one dimensional cellular automaton.
  5.  
  6.    Args:
  7.        num_cells: The integer width of the automaton.
  8.        num_gens: The number of generations to simulate.
  9.        rules: A list containing the four rules by which to update each cell, corresponding to the total of each set of neighbouring cells.
  10.    """
  11.     state = []
  12.    
  13.     # Randomly assign 0s or 1s to cells in the automaton.
  14.     for i in range(num_cells):
  15.         state.append(random.randint(0,1))
  16.        
  17.     # Print zeroth generation
  18.     print_state(state)
  19.  
  20.     # Print subsequent generations
  21.     for i in range(num_gens):
  22.         state = next_gen(state, rules)
  23.         print_state(state)
  24.  
  25. def next_gen(curr_gen, rules):
  26.     """Returns the next generation of a one dimensional cellular automaton.
  27.  
  28.    Args:
  29.        curr_gen: A list of 0s and 1s detailing the state of the current generation to base the next generation off of.
  30.        rules: A list of 4 0s or 1s determining the rules for the next generation.
  31.    Returns:
  32.        new_gen: A list of the same dimension as curr_gen.
  33.    """
  34.    
  35.     # Make an unlinked copy of curr_gen
  36.     new_gen = list(curr_gen)
  37.  
  38.     for i in range(0, len(curr_gen)):
  39.         sum_cells = 0
  40.        
  41.         if i>0: sum_cells += curr_gen[i-1]
  42.         sum_cells += curr_gen[i]
  43.         if i<len(curr_gen)-1: sum_cells += curr_gen[i+1]
  44.  
  45.         new_gen[i] = rules[sum_cells]
  46.  
  47.     return new_gen
  48.  
  49. def print_state(state):
  50.     """Prints the state of a 1D cellular automaton in one line."""
  51.    
  52.     s = ""
  53.     for cell in state: s += str(cell)
  54.     print(s)
  55.  
  56. # Check to make sure the arguments are correct, then run the function.
  57. args = sys.argv
  58.  
  59. if all([
  60.         len(args[1:])==6,
  61.         all(arg.isnumeric() for arg in args[1:]),
  62.         int(args[1])>0,
  63.         int(args[2])>=0,
  64.         all(arg in '01' for arg in args[-4:])
  65.     ]):
  66.     cellular_automaton(int(args[1]), int(args[2]), [int(arg) for arg in args[-4:]])
  67. else:
  68.     print("Usage: python 1DCellularAutomaton.py <cells> <generations> <rule0> <rule1> <rule2> <rule3>\nEx: python 1DCellularAutomaton.py 70 30 0 1 0 0")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement