'The code works but not for all of the inputs
I have an assignment in recursion.
The problem:
- A game board is defined by a list.
- Each list index,
(0: n-1)
is a row in the board, and the int value in each list index is the column (0:n-1
also). - There are towers on the board ( 1 in each row) so that the tower in row 5 and column 6 is :list[5] = 6
The first segment in the problem is to define a function that calculates the distance (only vertical and horizontal steps) between 2 given towers.
The 2nd segment is to define a function that gets a board, d-minimal distance and a row&col and returns True and assigns the tower if the the distance between the given row&col to any other tower above them (row-1 : 0) is greater than d.
The 3rd segment is to define a function that gets n(number of rows and columns) and a d minimal distance and with the aid of another recursive function, to return a board that answers the problem, meaning any board that correctly puts towers in the relevant size board with the correct minimum distance and if there is no solution return empty list.
I have code that works almost always and I'm trying to handle a specific case that bugs.
With the code below, the input n=13
, d=4
returns an empty list even though there is solution. The bug is caused by the fact that the code assigns the first available solution and not with judgement and therefore it causes the 7th row to have no place to put a tower. But if I took +1 index the rows 6,5,4 there would be a solution.
Please note that we are not allowed to use any loops nor any list methods except for len()
and append()
.
code:
def distance(row1, col1, row2, col2):
sum_distance = abs(col2 - col1) + abs(row1 - row2)
return sum_distance
def add_tower(board, d, row, col):
if row == 0:
board[row] = col
return True
for i in range(0, row):
temp = distance(i, board[i], row, col)
if d >= temp:
return False
board[row] = col
return True
def n_towers(n, d):
index_row = 0
index_col = 0
temp_board = [0] * n
if side_func(temp_board,n,d,index_row,index_col) == []:
return []
else:
return temp_board
def side_func(board,n,d,idx_row,idx_col):
if idx_row <= n-1:
if idx_col >= n:
return []
if add_tower(board,d,idx_row ,idx_col):
board[idx_row] = idx_col
return side_func(board,n,d,idx_row + 1,0)
else:
if idx_col <n:
return side_func(board,n,d,idx_row ,idx_col+1)
else:
idx_col = 0
return side_func(board,n,d,idx_row + 1,idx_col)
else:
return board
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|