国际象棋乐趣#6:国际象棋主教梦【难度:3级】:
答案1:
namespace myjinxin
{
using System;
public class Kata
{
public int[] ChessBishopDream(int[] BoardSize, int[] InitPosition, int[] InitDirection, int k){
int x = InitPosition[1];
int y = InitPosition[0];
int dx = InitDirection[1];
int dy = InitDirection[0];
bool flag = true; //loop until we have a pattern.
int count = 0; //to se how many iterations it takes to find a pattern.
while(flag)//look until we have a pattern.
{
count++;
//do moove.
x += dx;
y += dy;
//if out, invert direction, take back moove.
if(x<0)
{
x = 0;
dx *= -1;
}
if(x>BoardSize[1]-1)
{
x = BoardSize[1]-1;
dx *= -1;
}
if(y<0)
{
y = 0;
dy *= -1;
}
if(y>BoardSize[0]-1)
{
y = BoardSize[0]-1;
dy *= -1;
}
//if we end up having same x,y,dx,dy as start values, terminate, we have a pattern.
if((x == InitPosition[1]) && (dx == InitDirection[1]) &&
(y == InitPosition[0]) && (dy == InitDirection[0]))
flag = false;
}//end while
//Now we need to take modulo of that, from the initial k value...
//to get the x:th position. We know the steps, or count to get there.
int idx = k % count;
//iterate to that position....
for(int i = 0; i < idx; i++)
{
//do moove.
x += dx;
y += dy;
//if out, invert direction, take back moove.
if(x<0)
{
x = 0;
dx *= -1;
}
if(x>BoardSize[1]-1)
{
x = BoardSize[1]-1;
dx *= -1;
}
if(y<0)
{
y = 0;
dy *= -1;
}
if(y>BoardSize[0]-1)
{
y = BoardSize[0]-1;
dy *= -1;
}
}
//we have the position. Just send it back.
int[] pos = {
y,x};
return pos;
}
}
}
答案2:
namespace myjinxin
{
using System;
public class Kata
{
public int[] ChessBishopDream(int[] BoardSize, int[] InitPosition, int[] InitDirection, int k){
int x = getPos(BoardSize[0], InitPosition[0], InitDirection[0], k);
int y = getPos(BoardSize[1], InitPosition[1], InitDirection[1], k);
return new int[] {
x,y};
}
private static int getPos(int x, int p, int d, int c)
{
if (d > 0)
{
int np = (c + p) % (x * 2);
if (np >= x) return x * 2 - 1 - np