write a small JS function that, given an array of 0's and 1's, computes the next step of…
- User
write a small JS function that, given an array of 0's and 1's, computes the next step of the array, by applying a rewrite rule that sums 3 neighbors (mod 2), wrapping around (cell 0 interacts with last cell)
Assistant
Here is a function that does what you described:
function nextStep(arr) { const newArr = []; for (let i = 0; i < arr.length; i++) { const left = arr[i > 0 ? i - 1 : arr.length - 1]; const middle = arr[i]; const right = arr[(i + 1) % arr.length]; newArr.push((left + middle + right) % 2); } return newArr; }To explain:
- It creates a new array
newArrto store the next step - Loops through each cell in the input array
arr- Gets the left, middle and right cell, handling wrapping around at the edges
- Sums those 3 cells modulo 2 (to get 0 or 1)
- Pushes the sum to
newArr
- Returns the new array after processing all cells
- It creates a new array
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.