Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- public class CellularAutomaton {
- private int[] state;
- private int generation = 0;
- private int[][] pattern = {
- // neighbors(3) and new-state
- { 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, 1, 0, 0 }, { 0, 1, 1, 0 },
- { 1, 0, 0, 1 }, { 1, 0, 1, 1 }, { 1, 1, 0, 1 }, { 1, 1, 1, 1 }
- };
- public CellularAutomaton(int[] state) {
- if (state.length < 1) {
- throw new IllegalArgumentException("state length is short.");
- }
- this.state = new int[state.length + 2]; // 2 for side edge
- int i = 0;
- this.state[i++] = 0; // left edge
- for (; i < state.length + 1; ++i) {
- this.state[i] = state[i - 1];
- }
- this.state[i] = 0; // right edge
- }
- public CellularAutomaton next() {
- int[] new_state = new int[state.length];
- new_state[0] = new_state[state.length - 1] = 0;
- for (int p = 0; p < pattern.length; ++p) {
- for (int i = 0; i < state.length - 2; ++i) {
- if (state[i] == pattern[p][0]
- && state[i + 1] == pattern[p][1]
- && state[i + 2] == pattern[p][2]) {
- new_state[i + 1] = pattern[p][3];
- }
- }
- }
- state = new_state.clone();
- ++generation;
- return this;
- }
- public int getGeneration() {
- return generation;
- }
- public String toString() {
- return
- Integer.toString(getGeneration())
- + Arrays.toString(
- Arrays.copyOfRange(state, 1, state.length - 1));
- }
- public static void main(String[] args) {
- CellularAutomaton ca =
- new CellularAutomaton(new int[] { 0, 1, 0, 0, 0, 1, 0, 1 });
- System.out.println(ca);
- for (int i = 0; i < 10; ++i) {
- System.out.println(ca.next());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement