It is officially Monday so i can go ahead and place my intial solution. Well this was how i approached the problem.
I think my logics are straight forward. I created a struct to store Cannibals and Missionary. Then i used that struct to created a LEFTSIDE and a RIGHTSIDE.
To solve the crossing issue only a if statement coupled with a move heuristics was needed.
if( T.miss == T.can || T.miss == FALSE || T.miss == NUM )return x;
In defining a move scheme, I realised that there was only 3 possible moves when on the rightside and 3 when on the leftside.
Now i am aware and have always been aware that i could greatly reduce the LOC but i don't generally post those i just post intial solution. I am looking bad in my challenge so i may have to really revise it and post my 50 LOC but i doubt i shall. I shall instead humbly accept defeat.
Without further ado here is my solution:
Code:
// Name : DPD
// Program : River Crossing
// Description : This simulate a problem of 3 missionsries and 3 cannibals
// crossing a river.
// Date : AUG 3, 2005
// Last Updated: ----------
// Proposed mod: I can makde Right Move and leftMove one Function aand eliminate
// most of display to make program approximately 80 LOC
#include <stdio.h>
#include <conio.h>
#define NUM 3
enum mode{ FALSE, TRUE };
typedef struct
{
int miss;
int can;
}Players;
//After every move display current postion.
void Display( Players , Players );
//Accepts move from the righthand.
void LeftMove( Players *, Players * );
//Accepts move from the lefthand
void RightMove( Players *, Players * );
//Test to find a valid move.
int Validate( Players Moves[], Players *);
void main()
{
Players rightSide = {NUM,NUM};
Players leftSide = {0,0};
Display( rightSide, leftSide );
while( TRUE )
{
LeftMove( &leftSide, &rightSide );
Display( rightSide, leftSide );
if( leftSide.miss == NUM && leftSide.can == NUM )return;
RightMove( &leftSide, &rightSide );
Display( rightSide, leftSide );
}
}
void LeftMove( Players *leftSide, Players *rightSide )
{
Players Moves[3]= {{2,0 },{ 0,2 }, { 1,1 }};
int ans;
ans = Validate( Moves, leftSide );
leftSide->miss += Moves[ans].miss;
leftSide->can += Moves[ans].can;
rightSide->miss -= Moves[ans].miss;
rightSide->can -= Moves[ans].can;
}
void RightMove( Players *leftSide, Players *rightSide )
{
Players Moves[3]= { { 0,1 },{1,0 },{ 1,1 }};
int ans;
ans = Validate( Moves, rightSide );
rightSide->miss += Moves[ans].miss;
rightSide->can += Moves[ans].can;
leftSide->miss -= Moves[ans].miss;
leftSide->can -= Moves[ans].can;
}
int Validate( Players Moves[], Players *State )
{
int x;
Players T = {0,0};
for( x = 0; x < NUM; x++ )
{
T.miss = State->miss;
T.can = State->can;
T.miss += Moves[x].miss;
T.can += Moves[x].can;
if( T.miss == T.can || T.miss == FALSE || T.miss == NUM )return x;
}
return -1;
}
void Display( Players rightSide, Players leftSide )
{
printf("Left = M%d C%d Right = M%d C%d\n", leftSide.miss, leftSide.can,
rightSide.miss, rightSide.can );
getch();
}