Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys,random
- def cellular_automaton(num_cells, num_gens, rules):
- """Prints out generations of a one dimensional cellular automaton.
- Args:
- num_cells: The integer width of the automaton.
- num_gens: The number of generations to simulate.
- rules: A list containing the four rules by which to update each cell, corresponding to the total of each set of neighbouring cells.
- """
- state = []
- # Randomly assign 0s or 1s to cells in the automaton.
- for i in range(num_cells):
- state.append(random.randint(0,1))
- # Print zeroth generation
- print_state(state)
- # Print subsequent generations
- for i in range(num_gens):
- state = next_gen(state, rules)
- print_state(state)
- def next_gen(curr_gen, rules):
- """Returns the next generation of a one dimensional cellular automaton.
- Args:
- curr_gen: A list of 0s and 1s detailing the state of the current generation to base the next generation off of.
- rules: A list of 4 0s or 1s determining the rules for the next generation.
- Returns:
- new_gen: A list of the same dimension as curr_gen.
- """
- # Make an unlinked copy of curr_gen
- new_gen = list(curr_gen)
- for i in range(0, len(curr_gen)):
- sum_cells = 0
- if i>0: sum_cells += curr_gen[i-1]
- sum_cells += curr_gen[i]
- if i<len(curr_gen)-1: sum_cells += curr_gen[i+1]
- new_gen[i] = rules[sum_cells]
- return new_gen
- def print_state(state):
- """Prints the state of a 1D cellular automaton in one line."""
- s = ""
- for cell in state: s += str(cell)
- print(s)
- # Check to make sure the arguments are correct, then run the function.
- args = sys.argv
- if all([
- len(args[1:])==6,
- all(arg.isnumeric() for arg in args[1:]),
- int(args[1])>0,
- int(args[2])>=0,
- all(arg in '01' for arg in args[-4:])
- ]):
- cellular_automaton(int(args[1]), int(args[2]), [int(arg) for arg in args[-4:]])
- else:
- 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