Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
reading wiki solution in Clear category for Shooting Range by roman.bratishchev
# https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection
def shot(w1, w2, sp, lp):
x1,y1,x2,y2,x3,y3,x4,y4=*w1,*w2,*sp,*lp
if not(denom:=(x1-x2)*(y3-y4)-(y1-y2)*(x3-x4)): return -1 # parallel to the wall
t,u=((x1-x3)*(y3-y4)-(y1-y3)*(x3-x4))/denom,-((x1-x2)*(y1-y3)-(y1-y2)*(x1-x3))/denom
if 0<=t<=1 and u>=0: return round((1-2*abs(t-0.5))*100) # convert <0...1> interval to <0...100...0>
return -1 # outside the wall or in opposite direction
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. 19, 2024
Comments: