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 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

1from typing import List
2
3def cell_state_after_n_days(states: List[int], days: int) -> List[int]:
4    def get(i: int) -> int:
5        return states[i] if 0 <= i < len(states) else 0
6
7    for _ in range(days):
8        states = [
9            int(get(i - 1) != get(i + 1))
10            for i in range(len(states))
11        ]
12    return states
13
14if __name__ == '__main__':
15    states = [int(x) for x in input().split()]
16    days = int(input())
17    res = cell_state_after_n_days(states, days)
18    print(' '.join(map(str, res)))
19

Got a question?ย Ask the Teaching Assistantย anything you don't understand.

Still not clear? Ask in the Forum, ย Discordย orย Submitย the part you don't understand to our editors.

โ†
โ†‘TA ๐Ÿ‘จโ€๐Ÿซ