这题目的难点在于怎么由top和front判定原始die的各面的点数。
解决的方法还是要预设好所有情况,然后去匹配。
#include <string.h>
#include <stdio.h>
using namespace std;
int DetermineRight(int top, int front)
{
// table recording the possible states of a die
static int nDieStateTable[6][2] = {{2, 3}, {6, 3}, {2, 6}, {2, 1}, {1, 3}, {2, 4}};
int tmpFront = nDieStateTable[top - 1][0];
int tmpRight = nDieStateTable[top - 1][1];
while (front != tmpFront)
{
int temp = tmpRight;
tmpRight = 7 - tmpFront;
tmpFront = temp;
}
return tmpRight;
}
void RollTheDie(char direction, int &top, int &front, int &right, int &x, int &y)
{
int temp = top;
switch (direction)
{
case 'N' :
top = front, front = 7 - temp;
y ++;
break;
case 'S' :
top = 7 - front, front = temp;
y --;
break;
case 'E' :
top = 7 - right, right = temp;
x ++;
break;
case 'W' :
top = right, right = 7 - temp;
x --;
break;
default:
break;
}
}
int main(int argc, char *argv[])
{
//string szInput;
char szInput[255];
printf("Problem 2 by team x/n");
memset(szInput, 0, sizeof(szInput));
while( gets(szInput) != NULL)
{
int top = szInput[0] - '0';
int front = szInput[2] - '0';
// make sure that top and front are valid
if (top != front && top != 7 - front)
{
printf("/nInitial orientation: top =%2d front =%2d/nMoves:", top, front);
int right = DetermineRight(top, front);
int x = 0, y = 0;
for (size_t i = 4; szInput[i] != 0; i += 2)
{
printf(" %c", szInput[i]);
RollTheDie(szInput[i], top, front, right, x, y);
}
printf("/nFinal orientation and position: top =%2d front =%2d x =%4d y =%4d/n", top, front, x, y);
}
else
{
printf("/nInvalid initial orientation: top =%2d front =%2d/n", top, front);
}
memset(szInput, 0, sizeof(szInput));
}
printf("End of problem 2 by team x/n");
return 0;
}