Advertisement
Guest User

Untitled

a guest
Feb 20th, 2020
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.19 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. /**
  4.  * Model a 1D elementary cellular automaton.
  5.  *
  6.  * @author David J. Barnes and Michael Kölling
  7.  * @version  2016.02.29 - version 1
  8.  */
  9. public class Automaton
  10. {
  11.     // The number of cells.
  12.     private final int numberOfCells;
  13.     // The state of the cells.
  14.     private int[] state;
  15.    
  16.     /**
  17.      * Create a 1D automaton consisting of the given number of cells.
  18.      * @param numberOfCells The number of cells in the automaton.
  19.      * Exercise 7.27
  20.      */
  21.     public Automaton(int numberOfCells)
  22.     {
  23.         this.numberOfCells = numberOfCells;
  24.         state = new int[numberOfCells];
  25.         // Seed the automaton with a single 'on' cell in the middle.
  26.         state[numberOfCells / 2] = 1;
  27.     }
  28.    
  29.     /**
  30.      * Print the current state of the automaton.
  31.      */
  32.     public void print()
  33.     {
  34.         for(int cellValue : state) {
  35.             if(cellValue == 1) {
  36.                 System.out.print("*");
  37.             }
  38.             else {
  39.                 System.out.print(" ");
  40.             }
  41.         }
  42.         System.out.println();
  43.     }  
  44.    
  45.     /**
  46.      * Update the automaton to its next state.
  47.      */
  48.     public void update()
  49.     {
  50.         // Build the new state in a separate array.
  51.         int[] nextState = new int[state.length];
  52.         int left = 0;
  53.         int center = state[0];
  54.         for(int i = 0; i < state.length; i++) {
  55.             int right = i + 1 < state.length ? state[i + 1] : 0;
  56.             nextState[i] = calculateNextState(left, center, right);
  57.             left = center;
  58.             center = right;
  59.         }
  60.         state = nextState;
  61.     }
  62.    
  63.     /**
  64.      * Exercise 7.32
  65.      * Returns the calculation of the value of the next state.
  66.      * @param int left.
  67.      * @param int center.
  68.      * @param int right.
  69.      */
  70.     public int calculateNextState(int left, int center, int right)
  71.     {
  72.         int nextState = (left + center + right) % 2;
  73.         return nextState;
  74.     }
  75.  
  76.     /**
  77.      * Reset the automaton.
  78.      */
  79.     public void reset()
  80.     {
  81.         Arrays.fill(state, 0);
  82.         // Seed the automaton with a single 'on' cell.
  83.         state[numberOfCells / 2] = 1;
  84.     }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement