Amazon Online Assessment (OA) - Cell State After N Days

Eight houses, represented as cells, are arranged in a straight line. Each day every cell competes with its adjacent cells (neighbors). An integer value 1 represents an active cell and a value of 0 represents an inactive cell. If the neighbors on both the sides of a cell are either active or inactive, the cell becomes inactive on the next day; otherwise the cell becomes active. The two cells on each end have a single adjacent cell, so assume that the unoccupied space on the opposite side is an inactive cell. Even after updating the cell state, consider its previous state when updating the state of other cells. The state information of all cells should be updated simultaneously.

Write an algorithm to output the state of the cells after the given number of days.

Input

states, a list of integers representing the current state of cells

days, an integer representing the number of days

Output

Return a list of integers representing the state of the cells after the given number of days.

Examples

Example 1:

Input: states = [1, 0, 0, 0, 0, 1, 0, 0], days = 1
Output: [0, 1, 0, 0, 1, 0, 1, 0]

Example 2:

Input: states = [1, 1, 1, 0, 1, 1, 1, 1], days = 2
Output: [0, 0, 0, 0, 0, 1, 1, 0]

Try it yourself

Solutions

#!/usr/bin/env python3

from typing import List


def cell_state_after_n_days(states: List[int], days: int) -> List[int]:
    '''
    >>> cell_state_after_n_days([1, 0, 0, 0, 0, 1, 0, 0], 1)
    [0, 1, 0, 0, 1, 0, 1, 0]
    >>> cell_state_after_n_days([1, 1, 1, 0, 1, 1, 1, 1], 2)
    [0, 0, 0, 0, 0, 1, 1, 0]
    '''

    def get(i: int) -> int:
        return states[i] if 0 <= i < len(states) else 0

    for _ in range(days):
        states = [
            int(get(i - 1) != get(i + 1))
            for i in range(len(states))
        ]
    return states


def cell_state_after_n_days_(states: List[int], days: int) -> List[int]:
    '''
    >>> cell_state_after_n_days_([1, 0, 0, 0, 0, 1, 0, 0], 1)
    [0, 1, 0, 0, 1, 0, 1, 0]
    >>> cell_state_after_n_days_([1, 1, 1, 0, 1, 1, 1, 1], 2)
    [0, 0, 0, 0, 0, 1, 1, 0]
    '''

    for _ in range(days):
        p = 0
        for i in range(len(states) - 1):
            states[i], p = int(p != states[i + 1]), states[i]
        states[-1] = p
    return states


def cell_state_after_n_days__(states: List[int], days: int) -> List[int]:
    '''
    >>> cell_state_after_n_days__([1, 0, 0, 0, 0, 1, 0, 0], 1)
    [0, 1, 0, 0, 1, 0, 1, 0]
    >>> cell_state_after_n_days__([1, 1, 1, 0, 1, 1, 1, 1], 2)
    [0, 0, 0, 0, 0, 1, 1, 0]
    '''

    for _ in range(days):
        states = [
            int(a != b)
            for a, b in zip([0, *states[:-1]], [*states[1:], 0])
        ]
    return states


if __name__ == '__main__':
    import doctest
    doctest.testmod()