Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
get vector solution in Clear category for Find Enemy by kurosawa4434
DIRS = ['N', 'NE', 'SE', 'S', 'SW', 'NW']
def find_enemy(you, dir, enemy):
x1, y1 = ord(you[0]), int(you[1:])
x2, y2 = ord(enemy[0]), int(enemy[1:])
dx = abs(x1 - x2)
dy = y2 - y1
# e.g.
# __ __ __ __
# / \__/C1\__/ \__/ \
# \__/ \__/ \__/ \__/
# / \__/C2\__/ \__/ \
# \__/B2\__/ \__/ \__/
# /A3\__/C3\__/ \__/ \
# \__/B3\__/ \__/ \__/
# / \__/C4\__/ \__/ \
# \__/ \__/ \__/ \__/
# / \__/C5\__/ \__/ \
# \__/ \__/ \__/ \__/
#
# When you == 'A3' and enemy in column 'C',
# from C2 to C4 is same distance ( == dx ).
# Therefore lim_top : -1 = ( 2 - 3 )
# lim_bottom : +1 = ( 4 - 3 )
#
lim_top = (dx + x1 % 2) // 2 * -1
lim_bottom = (dx + (1 - x1 % 2)) // 2
# make vector dictionary
# e.g. you == 'A3' and enemy == 'C1'
# Then :
# vec = {'N':1, 'NE':2, 'SW':0, 'S':0, 'SW':0, 'NW':0}
#
vec = {d: 0 for d in DIRS}
if not (lim_top <= dy <= lim_bottom):
ns, lim_over = ('N', lim_top) if y1 > y2 else ('S', lim_bottom)
vec[ns] = abs(y1 - y2) - abs(lim_over)
dy_in_range = min(max(dy, lim_top), lim_bottom)
we = 'W' if x1 > x2 else 'E'
vec['N' + we] = abs(lim_bottom - dy_in_range)
vec['S' + we] = abs(lim_top - dy_in_range)
# rotate vector (turn to 'N')
#
# e.g.
# your direction == 'NE'
# vec = {'N':1, 'NE':2..} n_vec = {'N':2, 'NW':1..}
#
# / \__/ \__/ \__/ / \__/ \__/ \__/
# \__/ \__/ \__/ \ \__/E \__/ \__/ \
# / \__/ \__/E \__/ / \__/ \__/ \__/
# \__/ \__/ \__/ \ \__/ \__/ \__/ \
# / \__/ \__/ \__/ / \__/ \__/ \__/
# \__/ \__/ \__/ \ > \__/ \__/ \__/ \
# / \__/Y \__/ \__/ / \__/Y \__/ \__/
# \__/ \__/ \__/ \ \__/ \__/ \__/ \
# / \__/ \__/ \__/ / \__/ \__/ \__/
n_vec = {}
for d in range(len(DIRS)):
n_vec[DIRS[d - DIRS.index(dir)]] = vec[DIRS[d]]
# detect relational direction by n_vec.
if n_vec['N']:
r_dir = 'F'
elif n_vec['S']:
r_dir = 'B'
elif n_vec['NE'] or n_vec['SE']:
r_dir = 'R'
else:
r_dir = 'L'
return [r_dir, sum(d for d in vec.values())]
if __name__ == '__main__':
assert find_enemy('G5', 'N', 'G4') == ['F', 1], "N-1"
assert find_enemy('G5', 'N', 'I4') == ['R', 2], "NE-2"
assert find_enemy('G5', 'N', 'J6') == ['R', 3], "SE-3"
assert find_enemy('G5', 'N', 'G9') == ['B', 4], "S-4"
assert find_enemy('G5', 'N', 'B7') == ['L', 5], "SW-5"
assert find_enemy('G5', 'N', 'A2') == ['L', 6], "NW-6"
assert find_enemy('G3', 'NE', 'C5') == ['B', 4], "[watch your six!]"
assert find_enemy('H3', 'SW', 'E2') == ['R', 3], "right"
assert find_enemy('A4', 'S', 'M4') == ['L', 12], "true left"
assert find_enemy('C3', 'SE', 'A1') == ['B', 3], "Extra 1"
assert find_enemy('D3', 'NE', 'A1') == ['L', 4], "Extra 2"
assert find_enemy('A1', 'SW', 'Z9') == ['B', 25], "Extra 3"
print("You are good to go!")
Nov. 26, 2016