(p,a,b,c,d)->{c^=a/4*7;a^=a/4*7;d^=b/4*7;b^=b/4*7;int x=c<a?a-c:c-a,y=d<b?b-d:d-b,z=(x^=y^(y=y<x?y:x))-y;return p<1?x:p<2?z*y<1?1:2:p<3?2-z%2:p<4?x+y<2?3:(a<c?a+b:c+d)+x<2|x==2&z<1?4:z+2*Math.ceil((y-z)/(y>z?3:4.)):z<1?1:~z*2&2;}
在线尝试!
说明
- 该板是基于0的板。
- 返回值是一个整数,表示为双精度型。永远不会有任何小数部分。
码:
(p,a,b,c,d)->{ // double-returning lambda.
// p is the piece-type (0: king, 1: queen, 2: rook, 3: knight, 4: bishop)
// a is the origin-X
// b is the origin-Y
// c is the destination-X
// d is the destination-Y
c^=a/4*7;a^=a/4*7; // Mirror board if origin is in the top part of the board
d^=b/4*7;b^=b/4*7; // Mirror board if origin is in the left part of the board
int x=c<a?a-c:c-a, // x is the X-distance between a and c
y=d<b?b-d:d-b, // y is the Y-distance between b and d
z=(x^=y^(y=y<x?y:x))-y; // z is the delta between x and y
// also, swap x and y if necessary so that x is the greater value.
// At this point,
// x cannot be 0 (because the two positions are different)
// z<1 means the origin and destination are on the same diagonal
// y<1 means the origin and destination are on the same horizontal/vertical line
return
p<1?x: // For a king, just take the max distance.
p<2?z*y<1?1:2: // For a queen, just move once if in direct line, or twice.
p<3?2-z%2: // For a rook, just move once if on the same horizontal or vertical line, or twice
p<4? // For a knight,
x+y<2?3: // Hardcode 3 if moving to the next horizontal/vertical square
(a<c?a+b:c+d)+x<2|x==2&z<1?4: // Hardcode 4 if moving 2 cases in diagonal or one case in diagonal in a corner.
z+2*Math.ceil((y-z)/(y>z?3:4.)): // Compute the number of moves necessary for the usual cases
z<1?1: // For a bishop, hardcode 1 if they are on the same diagonal
~z*2&2; // Return 2 if they have the same parity else 0.
}
学分