main.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. function read(cb) {
  2. require("fs").readFile('./input', 'utf8', (err, data) => {
  3. var world = new World();
  4. data.split("\n").forEach((l) => {
  5. if (l.startsWith("initial state: ")) {
  6. world.initializeState(l.substr(15));
  7. } else {
  8. var r = /([.#]+) => ([.#])/.exec(l);
  9. if (r)
  10. world.rules[r[1]] = r[2];
  11. }
  12. });
  13. cb(world);
  14. });
  15. }
  16. function World() {
  17. this.initialState = [];
  18. this.rules = [];
  19. this.state = [];
  20. this.loop = 0;
  21. this.offset = 0;
  22. }
  23. World.prototype.initializeState = function(li) {
  24. for (var i =0, len = li.length; i < len; ++i)
  25. this.initialState.push(li[i] == '#');
  26. this.state = this.initialState;
  27. }
  28. World.prototype.arrToString = function(pos) {
  29. var result = "";
  30. for (var i =-2; i <= 2; ++i)
  31. result += (this.initialState[pos +i] ? '#' : '.');
  32. return result;
  33. }
  34. World.prototype.step = function() {
  35. this.state = [];
  36. var offset = [];
  37. for (var i =-2; i < 0; ++i) {
  38. var state = this.rules[this.arrToString(i)];
  39. if (state == '#')
  40. offset[-i] = true;
  41. else if (state == '.')
  42. offset[-i] = false;
  43. }
  44. for (var i =0, len = this.initialState.length +2; i < len; ++i) {
  45. var state = this.rules[this.arrToString(i)];
  46. if (state == '#')
  47. this.state[i] = true;
  48. else if (state == '.')
  49. this.state[i] = false;
  50. }
  51. if (offset[2]) {
  52. this.state.splice(0, 0, offset[2], offset[1])
  53. this.offset += 2;
  54. }
  55. else if (offset[1]) {
  56. this.state.splice(0, 0, offset[1])
  57. ++this.offset;
  58. }
  59. this.initialState = this.state;
  60. ++this.loop;
  61. }
  62. World.prototype.count = function() {
  63. var result = 0;
  64. for (var i =0, len = this.initialState.length; i < len; ++i)
  65. if (this.initialState[i])
  66. result += i -this.offset;
  67. return result;
  68. }
  69. World.prototype.run = function(max) {
  70. for (var i =0; i < max; ++i)
  71. this.step();
  72. }
  73. function ex1() {
  74. read(world => {
  75. world.run(20);
  76. console.log(world.count());
  77. });
  78. }
  79. function ex2() {
  80. read(world => {
  81. world.run(500);
  82. console.log(world.count() +(50000000000 -500) *36);
  83. });
  84. }
  85. ex1();
  86. ex2();