Advertisement
cd62131

CellularAutomaton

Jun 7th, 2017
376
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.71 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class CellularAutomaton {
  4.   private int[] state;
  5.   private int generation = 0;
  6.   private int[][] pattern = {
  7.       // neighbors(3) and new-state
  8.       { 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, 1, 0, 0 }, { 0, 1, 1, 0 },
  9.       { 1, 0, 0, 1 }, { 1, 0, 1, 1 }, { 1, 1, 0, 1 }, { 1, 1, 1, 1 }
  10.   };
  11.  
  12.   public CellularAutomaton(int[] state) {
  13.     if (state.length < 1) {
  14.       throw new IllegalArgumentException("state length is short.");
  15.     }
  16.     this.state = new int[state.length + 2]; // 2 for side edge
  17.     int i = 0;
  18.     this.state[i++] = 0; // left edge
  19.     for (; i < state.length + 1; ++i) {
  20.       this.state[i] = state[i - 1];
  21.     }
  22.     this.state[i] = 0; // right edge
  23.   }
  24.  
  25.   public CellularAutomaton next() {
  26.     int[] new_state = new int[state.length];
  27.     new_state[0] = new_state[state.length - 1] = 0;
  28.     for (int p = 0; p < pattern.length; ++p) {
  29.       for (int i = 0; i < state.length - 2; ++i) {
  30.         if (state[i] == pattern[p][0]
  31.             && state[i + 1] == pattern[p][1]
  32.             && state[i + 2] == pattern[p][2]) {
  33.           new_state[i + 1] = pattern[p][3];
  34.         }
  35.       }
  36.     }
  37.     state = new_state.clone();
  38.     ++generation;
  39.     return this;
  40.   }
  41.  
  42.   public int getGeneration() {
  43.     return generation;
  44.   }
  45.  
  46.   public String toString() {
  47.     return
  48.         Integer.toString(getGeneration())
  49.         + Arrays.toString(
  50.             Arrays.copyOfRange(state, 1, state.length - 1));
  51.   }
  52.  
  53.   public static void main(String[] args) {
  54.     CellularAutomaton ca =
  55.         new CellularAutomaton(new int[] { 0, 1, 0, 0, 0, 1, 0, 1 });
  56.     System.out.println(ca);
  57.     for (int i = 0; i < 10; ++i) {
  58.       System.out.println(ca.next());
  59.     }
  60.   }
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement