(generation, rule)
| 65 | * @returns {(0 | 1)[]} The next generation according to the inputted rule |
| 66 | */ |
| 67 | export function getNextElementaryGeneration(generation, rule) { |
| 68 | const NUM_ELEMENTARY_NEIGHBORHOOD_STATES = 8 |
| 69 | const MIN_RULE = 0 |
| 70 | const MAX_RULE = 255 |
| 71 | |
| 72 | if (!Number.isInteger(rule)) { |
| 73 | throw new Error( |
| 74 | `Rule must be an integer between the values 0 and 255 (got ${rule})` |
| 75 | ) |
| 76 | } |
| 77 | if (rule < MIN_RULE || rule > MAX_RULE) { |
| 78 | throw new RangeError( |
| 79 | `Rule must be an integer between the values 0 and 255 (got ${rule})` |
| 80 | ) |
| 81 | } |
| 82 | |
| 83 | const binaryRule = rule |
| 84 | .toString(2) |
| 85 | .padStart(NUM_ELEMENTARY_NEIGHBORHOOD_STATES, '0') |
| 86 | const ruleData = binaryRule.split('').map((bit) => Number.parseInt(bit)) // note that ruleData[0] represents "all alive" while ruleData[7] represents "all dead" |
| 87 | const output = new Array(generation.length) |
| 88 | const LEFT_DEAD = 4 // 100 in binary |
| 89 | const MIDDLE_DEAD = 2 // 010 in binary |
| 90 | const RIGHT_DEAD = 1 // 001 in binary |
| 91 | |
| 92 | for (let i = 0; i < generation.length; i++) { |
| 93 | let neighborhoodValue = LEFT_DEAD | MIDDLE_DEAD | RIGHT_DEAD |
| 94 | |
| 95 | if (i - 1 > 0 && generation[i - 1] === 1) { |
| 96 | neighborhoodValue ^= LEFT_DEAD |
| 97 | } |
| 98 | |
| 99 | if (generation[i] === 1) { |
| 100 | neighborhoodValue ^= MIDDLE_DEAD |
| 101 | } |
| 102 | |
| 103 | if (i + 1 < generation.length && generation[i + 1] === 1) { |
| 104 | neighborhoodValue ^= RIGHT_DEAD |
| 105 | } |
| 106 | |
| 107 | output[i] = ruleData[neighborhoodValue] |
| 108 | } |
| 109 | |
| 110 | return output |
| 111 | } |
no test coverage detected