Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Shooting Range by Rounin
import math
def distance(a, b):
return math.sqrt((b[0]-a[0])**2+(b[1]-a[1])**2)
def shot(wall1, wall2, shot_point, later_point):
wall_slope = (math.inf if wall2[0] == wall1[0] else (wall2[1]-wall1[1])/(wall2[0]-wall1[0]))
wall_constant = (0 if wall_slope == math.inf else wall1[1]-(wall1[0]*wall_slope))
shot_slope = (math.inf if later_point[0] == shot_point[0] else (later_point[1]-shot_point[1])/(later_point[0]-shot_point[0]))
shot_constant = (0 if shot_slope == math.inf else shot_point[1]-(shot_point[0]*shot_slope))
if shot_slope == wall_slope:
return -1
elif abs(wall_slope) == math.inf:
intersection_x = wall1[0]
intersection_y = shot_point[1]+(wall1[0]-shot_point[0])*shot_slope
elif abs(shot_slope) == math.inf:
intersection_x = shot_point[0]
intersection_y = wall1[1]+(shot_point[0]-wall1[0])*wall_slope
else:
intersection_x = (shot_constant-wall_constant)/(wall_slope-shot_slope)
intersection_y = wall_constant+intersection_x * wall_slope
intersection = [intersection_x, intersection_y]
wall_length = distance(wall1, wall2)
distance1 = distance(wall1, intersection)
distance2 = distance(wall2, intersection)
if wall_length == 0 or distance1 > wall_length or distance2 > wall_length or distance(later_point, intersection) > distance(shot_point, intersection):
return -1
try:
return (0 if wall_length == 0 else round(100.0*(1.0-abs(distance2-distance1)/wall_length)))
except:
return -1
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert shot((2, 2), (5, 7), (11, 2), (8, 3)) == 100, "1st case"
assert shot((2, 2), (5, 7), (11, 2), (7, 2)) == 0, "2nd case"
assert shot((2, 2), (5, 7), (11, 2), (8, 4)) == 29, "3th case"
assert shot((2, 2), (5, 7), (11, 2), (9, 5)) == -1, "4th case"
assert shot((2, 2), (5, 7), (11, 2), (10.5, 3)) == -1, "4th case again"
Oct. 18, 2017