|
1 | 1 | class Plants { |
2 | 2 | constructor (initial, rules) { |
3 | 3 | this.generations = [] |
| 4 | + this.boundaryBuffers = [0, 0] |
4 | 5 | this.rules = {} |
5 | 6 | this._setInitialGeneration(initial) |
6 | 7 | if (rules && rules.length > 0) { |
7 | 8 | rules.forEach((rule) => { |
8 | 9 | this.addRule(rule) |
9 | 10 | }) |
10 | 11 | } |
| 12 | + this.boundaryBuffers = this.getBoundaryBuffers() |
11 | 13 | } |
12 | 14 |
|
13 | 15 | _setInitialGeneration (initial) { |
@@ -63,11 +65,14 @@ class Plants { |
63 | 65 | state: state |
64 | 66 | } |
65 | 67 | }) |
66 | | - // Add 2 pots at the beginning and end to support future generation |
67 | | - for (let x = 1; x <= 2; x++) { |
| 68 | + |
| 69 | + // Padd the list to support future generation |
| 70 | + for (let x = 1; x <= this.boundaryBuffers[0]; x++) { |
68 | 71 | const first = nextGen[0].position |
69 | | - const last = nextGen[nextGen.length - 1].position |
70 | 72 | nextGen.splice(0, 0, { position: first - 1, state: '.' }) |
| 73 | + } |
| 74 | + for (let x = 1; x <= this.boundaryBuffers[1]; x++) { |
| 75 | + const last = nextGen[nextGen.length - 1].position |
71 | 76 | nextGen.push({ position: last + 1, state: '.' }) |
72 | 77 | } |
73 | 78 |
|
@@ -100,6 +105,40 @@ class Plants { |
100 | 105 | }, [0, 0]) |
101 | 106 | } |
102 | 107 |
|
| 108 | + /** |
| 109 | + * Rules need empty pots lef/right of row for verification. Figures out the number of pots we need |
| 110 | + * to add to the left/right of a row |
| 111 | + * @returns {Array} [left, right] necessary buffer size of first and last pots |
| 112 | + */ |
| 113 | + getBoundaryBuffers () { |
| 114 | + let buffers = [0, 0] |
| 115 | + Object.keys(this.rules).filter((rule) => this.rules[rule] === '#').forEach((rule) => { |
| 116 | + // For left edge |
| 117 | + for (let x = 0; x < rule.length; x++) { |
| 118 | + if (rule.substr(x, 1) === '.') { |
| 119 | + let y = x + 1 |
| 120 | + buffers[0] = Math.max(buffers[0], y) |
| 121 | + } else { |
| 122 | + // break the loop when we encounter a # |
| 123 | + x = rule.length |
| 124 | + break |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + for (let x = rule.length - 1; x >= 0; x--) { |
| 129 | + if (rule.substr(x, 1) === '.') { |
| 130 | + let y = rule.length - x |
| 131 | + buffers[1] = Math.max(buffers[1], y) |
| 132 | + } else { |
| 133 | + // break the loop when we encounter a # |
| 134 | + x = -1 |
| 135 | + break |
| 136 | + } |
| 137 | + } |
| 138 | + }) |
| 139 | + return buffers |
| 140 | + } |
| 141 | + |
103 | 142 | /** |
104 | 143 | * Generates a visual display of the pots in all generations. Accepts optional boundaries. |
105 | 144 | * @param {Number} start First pot to include |
|
0 commit comments