Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cell Complete Problem (XOR)
/*
There is a colony of 8 cells arranged in a straight line where each day every cell competes with its adjacent cells(neighbour). Each day, for each cell, if its neighbours are both active or both inactive, the cell becomes inactive the next day,. otherwise itbecomes active the next day.
Assumptions: The two cells on the ends have single adjacent cell, so the other adjacent cell can be assumsed to be always inactive. Even after updating the cell state. consider its pervious state for updating the state of other cells. Update the cell informationof allcells simultaneously.
Write a fuction cellCompete which takes takes one 8 element array of integers cells representing the current state of 8 cells and one integer days representing te number of days to simulate. An integer value of 1 represents an active cell and value of 0 represents an inactive cell.
*/
function changeState(states) {
let temp = []
const len = states.length
const virtualCell = 0
for (var i = 0; i < len; i++) {
let currCell = states[0]
if (i === 0) {
currCell = states[1] ^ virtualCell
} else if (i === len-1) {
currCell = states[len-2] ^ virtualCell
} else {
currCell = states[i-1] ^ states[i+1]
}
temp[i] = currCell
}
return temp
}
function cellCompete(states, days)
{
let newStates = states
for (let j = 0; j < days; j++) newStates = changeState(newStates)
return newStates
}
const res = cellCompete([1,1,1,0,1,1,1,1], 2)
// output should be [0,0,0,0,0,1,1,0]
/*
My approach to this solution:
- First identify which logical operator gives us the following outcome:
0 0 => 0
0 1 => 1
1 0 => 1
1 1 => 0
So this is the xor operator
- Next step was to identify edge cases (first cell and last cell comparison (virtual cells))
- Then i figured another improtant part of the problem was to make sure
that the temp array is not polluted with previous values i.e: (let temp = [] vs let temp = states)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.