<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title></title>
  <link data-require="bootstrap-css" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
  <link rel="stylesheet" href="style.css" />
</head>

<body>
  <div class="container">
    <div class="page-header">
      <h4>Elementary Cellular Automata</h4>
    </div>
    <div class="row">
      <div class="col-md-12">
        <div class="wolfram-value alert alert-warning alert-dismissible hidden" role="alert">
  <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
  <strong>Error:</strong> All Wolfram values must be between 1 and 255
</div>
      </div>
    </div>
    <div class="row">
      <div class="col-md-12">
        <form class="form-horizontal" role=form>
          <div class="form-group">
            <label for="wolframValue" class="col-sm-2 control-label">Wolfram Value:</label>
            <div class="col-sm-4">
              <input id="wolframValueInput" class="form-control" type=number min="1" max="255" />
            </div>
          </div>
          <div class="form-group">
            <label for="iterations" class="col-sm-2 control-label">Iterations:</label>
            <div class="col-sm-4">
              <input id="iterations" class="form-control" type=number />
            </div>
          </div>
          <div class="form-group">
            <label for="initialValue" class="col-sm-2 control-label">Starting Value (bits):</label>
            <div class="col-sm-4">
              <input id="initialValueInput" class="form-control" type=text value="000000000001000000000000" />
            </div>
          </div>
          <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
              <button class="btn btn-default" id="submitButton">Submit</button>
            </div>
          </div>
        </form>
      </div>
    </div>
    <div class="row">
      <div class="col-md-12">
        <hr/>
        <div id="result"></div>
      </div>
    </div>
  </div>
  <script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.4.13/d3.min.js"></script>
  <script src="script.js"></script>
</body>

</html>
var btn = document.getElementById('submitButton');
var closeBtn = document.querySelector('.close');

function populateBitArray(val) {
  var i;
  var data = [];
  for (i = 0; i < 8; i++) {
    data[i] = (val >> i) & 1;
  }
  return data.reverse();
}


var stack = [];
var initialRules = [
  [1, 1, 1],
  [1, 1, 0],
  [1, 0, 1],
  [1, 0, 0],
  [0, 1, 1],
  [0, 1, 0],
  [0, 0, 1],
  [0, 0, 0]
]


  function newGeneration(arr, lookupTable) {
    var newGen = [];
    var len = arr.length;
    var firstCell,
      secondCell,
      thirdCell,
      lookupKey,
      outcome;
    arr.forEach(function(val, idx) {
      if (idx === 0) {
        firstCell = arr[len - 1];
        secondCell = arr[0];
        thirdCell = arr[1];
        lookupKey = [firstCell, secondCell, thirdCell];
        outcome = lookupTable[lookupKey.toString()];
        newGen[0] = outcome;
      } else if (idx === len - 1) {
        firstCell = arr[len - 2];
        secondCell = arr[len - 1];
        thirdCell = arr[0];
        lookupKey = [firstCell, secondCell, thirdCell];
        outcome = lookupTable[lookupKey];
        newGen[len - 1] = outcome;
      } else {
        lookupKey = [arr[idx - 1], arr[idx], arr[idx + 1]];
        outcome = lookupTable[lookupKey];
        newGen[idx] = outcome;
      }
    });
    return newGen;
  }

var svg = d3.select('#result')
  .append('svg');


function renderGraph(svg, data, i) {
  svg
  .attr('width', 1200)
  .attr('height', 1200)
  .append('g')
  .attr("class", "group parent")
  .selectAll('.cell' + i)
  .data(data)
  .enter()
  .append('rect')
  .attr("class", "cell" + i)
  .attr("width", 15)
  .attr("height", 15)
  .attr("y", 60 + (i * 15))
  .attr("x", function(d, i) { return i * 15 + 60; })
  .attr('stroke', 'white')
  .attr('stroke-width', 1)
  .attr("fill", function(d) { return d > 0 ? "black" : "none"} );
}

closeBtn.onclick = function(e) {
  e.preventDefault();
  var warning = document.querySelector(".wolfram-value.alert");
  warning.style.cssText = "display:none !important; visibility:hidden !important";
}

btn.onclick = function(e) {
  e.preventDefault();
  d3.selectAll(".group.parent").remove();
  var i;
  var wolframValueEl = document.getElementById('wolframValueInput');
  if (wolframValueEl.value > 255 || wolframValueEl < 1) {
    var warning = document.querySelector(".wolfram-value.alert");
    warning.style.cssText = "display:block !important; visibility:visible !important";
    return false;
  }
  var iterationsEl = document.getElementById('iterations');
  var initialValueEl = document.getElementById('initialValueInput');
  var iterations = iterationsEl.value;
  // Get value and convert to unsigned integer
  var wolframValue = wolframValueEl.value >>> 0;
  var initialConditionsArr = Array.prototype
    .map.call(initialValueEl.value, function(v) {
      return v;
    })
  .map(Number);
  var arr = populateBitArray(wolframValue);
  var lookupTable = {};
  var stack = [];
  initialRules.forEach(function(val, idx) {
    lookupTable[val] = arr[idx];
  });
  renderGraph(svg, initialConditionsArr, 0)
  var lastData = newGeneration(initialConditionsArr, lookupTable);
  stack.push(lastData);
  for (i = 0; i < iterations; i++) {
    var prev = stack.pop();
    console.log("last data", prev);
    renderGraph(svg, prev, i+1);
    var secondGen = newGeneration(prev, lookupTable);
    stack.push(secondGen);
  }
};
/* Put your css in here */

h1 {
  color: red;
}

.table {
  margin: 30px 50px 0px;
  width: 50%;
}
## Elementary Cellular Automata

Easy generation of elementary cellular automata using arbitrary Wolfram values.

### The MIT License (MIT)

Copyright (c) 2014 Eric S. Bullington

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.