Looking for a better solution to retrieving the values in a 2D array in a clockwise direction retrieving the values and add to a one dimensional array.
board = [[1, 4, 0, 5, 0],
[0, 7, 3, 0, 0],
[0, 6, 0, 9, 0],
[0, 0, 0, 2, 0]]
Function corkscrew()
which, given a two-dimensional list of integers,
shows the current player in each square from the
top left square to the center, going clockwise:
"""
+------------------+
|
+--------------+ |
| | |
| +------> | |
| | | |
| +----------+ |
| |
+------------------+
"""
For example, given the board array the function should return the following list:
[1, 4, 0, 5, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 7, 3, 0, 9, 0, 6]
Current Solution:
def get_row(board, index):
"""Generator to return the row value at the specified
index(i.e column value)."""
try:
for v in board.pop(index):
yield v
except IndexError:
raise StopIteration
def get_column(board, index):
for row in board:
try:
yield row.pop(index)
except IndexError:
raise StopIteration
def get_values(board):
"""Generator to return the values in a specific row."""
start = 0
operations = ['right', 'down', 'left', 'up'] * 2 + ['right']
for operation in operations:
row = []
if operation == 'right':
row = list(get_row(board, start))
start = len(row) - 1
elif operation == 'down':
row = list(get_column(board, start))
start = len(row)
elif operation == 'left':
row = list(reversed(list(get_row(board, start - 1))))
elif operation == 'up':
if board and board[0]:
start = start + 1 - len(board[0])
row = get_column(board, start)
for v in row:
yield v
def corkscrew(board):
"""Returns one dimensional array in going clockwise."""
new_board = []
# Clockwise pattern
values = get_values(board)
new_board.extend(values)
return new_board