diff --git a/src/modules/automata.js b/src/modules/automata.js index 4fb914c..e8ee506 100644 --- a/src/modules/automata.js +++ b/src/modules/automata.js @@ -20,14 +20,31 @@ function evolve1d(state, rules) { } // create a 2D board from a 1D CA initial state +// function createBoard(state, rules, height) { +// function createBoardAcc(s, h, acc) { +// if (h === 0) return acc; +// const newState = evolve1d(s, rules); +// const newAcc = acc.concat([s]); +// return createBoardAcc(newState, h - 1, newAcc); +// } +// return createBoardAcc(state, height, []); +// } + +// performance "choke point" in full imperative function createBoard(state, rules, height) { - function createBoardAcc(s, h, acc) { - if (h === 0) return acc; - const newState = evolve1d(s, rules); - const newAcc = acc.concat([s]); - return createBoardAcc(newState, h - 1, newAcc); + var board = []; + let prevState = []; + for (let i = 0; i < height; i++) { + let nextState = []; + if (i == 0) { + nextState = evolve1d(state, rules); + } else { + nextState = evolve1d(prevState, rules); + } + board = board.concat([nextState]); + prevState = nextState; } - return createBoardAcc(state, height, []); + return board; } // Find the neighbor of a given cell in a 2D CA board