Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
BFS for distance, first step for directions solution in Clear category for Find Enemy by kdim
"""
1 - the distance will be considered by the BFS algorithm
2 - the direction will be determined by the first step i.e.
if you take the first step towards the enemy to the NE or SE, then the enemy is on the Right,
if you take the first step towards the enemy to the N, then the enemy on the Front,
etc.
3 - rotate the direction will be with indices of array of directions
"""
def find_enemy(you, dir, enemy):
def neighbours(x): # get all neibors near the cell
return [go(x, d) for d in directions if go(x, d)]
def go(x, d): # get next of cell - x, according to direction - d
if ord(x[0]) % 2:
delta = {'N': (0, -1), 'NE': (1, -1), 'SE': (1, 0),
'S': (0, 1), 'SW': (-1, 0), 'NW': (-1, -1)}
else:
delta = {'N': (0, -1), 'NE': (1, 0), 'SE': (1, 1),
'S': (0, 1), 'SW': (-1, 1), 'NW': (-1, 0)}
i, j = delta[d]
s, n = ord(x[0]) + i, int(x[1]) + j
return chr(s) + str(n) if 65 <= s <= 90 and 0 <= n <= 10 else ''
def bfs(start, end): # get distance between start and end cells
visited = set([start])
queue = [set([start])]
step = 0
while end not in visited:
n = set(sum((neighbours(i) for i in queue.pop(0)), []))
queue.append(n - visited)
visited |= n
step += 1
return step
directions = ['N', 'NE', 'SE', 'S', 'SW', 'NW']
translate = {'NE': 'R', 'SE': 'R', 'NW': 'L', 'SW': 'L', 'N': 'F', 'S': 'B'}
distance = bfs(you, enemy) # get distance
direction = [d for d in directions if go(you, d) and distance > bfs(go(you, d), enemy)] # list of directions where I should go to find the enemy
# rotate the direction, and get with minimal len,
# F has priority over the NW/NE
direction = min((directions[directions.index(d) - directions.index(dir)] for d in direction), key=len)
for i, j in translate.items(): # translate direction to F, B, L, R
direction = direction.replace(i, j)
return [direction, distance]
Feb. 9, 2021
Comments: