我在搞乱按位运算,想实现一个简单的逻辑难题,你有一只狐狸(狼)、鸡(鹅)、谷物(玉米)和一个试图过河的人。我使用每个位的前 4 位来表示它们在河的哪一侧。
我在尝试实现逻辑时遇到了一些麻烦。
如何检查这两位是 1 还是 0 但不是 1 和 0?
int game()
{
int state = 0;
int done = 0;
while (!done)
{
int input = 0;
input = move();
/*
0000 0000
|||\_grain
||\__chicken
|\___fox
\____person
0 = left side of the river
1 = right side
*/
if (input == 3)// Moves person and grain
{
// Move the grain if the person is on the same side.
if (!(state & 1 << 3 ^ state & 1<< 0))
{
state ^= 1 << 3;
state ^= 1 << 0;
}
else
{
// Always switch the person no matter what
state ^= 1 << 3;
}
}
else if (input == 2) // Moves person and chicken
{
// Move Chicken only if person is on the same side
if (!(state & 1 << 3 ^ state & 1<< 1))
{
state ^= 1 << 3;
state ^= 1 << 1;
}
else
{
// Always switch the person no matter what
state ^= 1 << 3;
}
}
else if (input == 1)// Moves person and fox
{
// Move the fox if the person is on the same side.
if (!(state & 1 << 3 ^ state & 1<< 2))
{
state ^= 1 << 3;
state ^= 1 << 2;
}
else
{
// Always switch the person no matter what
state ^= 1 << 3;
}
}
// Fox and Chicken on one side and person on the other = lost
if ((state & 1 << 2 && state & 1 << 1) && ~(state & 1 << 3))
{
printf("Failed\n");
}
}
return 1;
}
我猜按位检查会是更优雅的代码,但似乎更痛苦。当我厌倦了用按位逻辑将头撞到墙上时,我总是会这样做。
int game()
{
int state = 0;
int done = 0;
while (!done)
{
int input = 0;
input = move();
/*
0000 0000
| | | \_grain
| | \__chicken
| \___fox
\____person
0 = left side of the river
1 = right side
*/
if (input == 3)// Moves person and grain
{
// Are they on the same side?
if (state == 9 || state == 11 || state == 13 || state == 15 ||
state == 0 || state == 2 || state == 4 || state == 6)
{
// Move the person and grain
state ^= 1 << 3;
state ^= 1 << 0;
}
else
{
state ^= 1 << 3;
}
}
else if (input == 2) // Moves person and chicken
{
// Are they on the same side?
if (state == 10 || state == 11 || state == 14 || state == 15 ||
state == 0 || state == 1 || state == 4 || state == 5)
{
// Move the person and chicken
state ^= 1 << 3;
state ^= 1 << 1;
}
else
{
state ^= 1 << 3;
}
}
else if (input == 1)// Moves person and fox
{
// Are they on the same side?
if (state == 12 || state == 13 || state == 14 || state == 15 ||
state == 0 || state == 1 || state == 2 || state == 3)
{
// Move the person and fox
state ^= 1 << 3;
state ^= 1 << 2;
}
else
{
state ^= 1 << 3;
}
}
else
{
// Always switch the person no matter what
state ^= 1 << 3;
}
//Check if you won or lost
if (state == 3 || state == 6 || state == 8 || state == 9 || state == 12) // Lost
{
return 0;
}
if (state == 15) // Won
{
return 1;
}
}
return 1;
}