I was trying to solve a king move(chess) task. I found out that king can move only if it's coordinates -1 <= x1-x2 and y1-y2 <= 1
.
My code is:
x1 = int(input()) #cuurent x-position
y1 = int(input()) #current y-position
x2 = int(input()) #estimated x-position
y2 = int(input()) #estimated y-position
if -1 <= x1-x2 and y1-y2 <= 1: #king can move to the x2-y2 from x1-y1
print('YES')
else: #king can't move to the x2-y2 from x1-y1
print('NO')
I works fine with all 'YES' moves I could find, but it doesn't work with some 'NO' moves, such as:
x1=4, y1=4, x2=2, y2=6 or x1=4, y1=4, x2=4, y2=6
. And I have no idea why, because: 4-4=0, but 4-6=-2 and -2 is less then -1.
A king can move if the absolute difference between the co-ordinates is less than or equal to 1.
So, write:
if abs(x1-x2) <= 1 and abs(y1-y2) <= 1: #king can move to the x2-y2 from x1-y1
print('YES')
else: #king can't move to the x2-y2 from x1-y1
print('NO')
This is because the co-ordinates you are moving from could be greater/lesser than the co-ordinates you are moving to, but you know that they differ by at most 1.