Please have a look at the following code
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
enum Movement{STAND,WALK,RUN,CRAWL};
Movement state = (Movement)(1+rand()%4);
for(int i=0;i<100;i++)
{
cout << state << endl;
switch(state)
{
case STAND:
cout << "You can walk or crawl" << endl;
while(state==WALK || state==CRAWL){
state = (Movement)(1+rand()%4);}
break;
case WALK:
cout << "You can stand or run" << endl;
while(state==STAND || state==RUN){
state = (Movement)(1+rand()%4);}
break;
case RUN:
cout << "You can walk" << endl;
while(state==WALK){
state = (Movement)(1+rand()%4);}
break;
default:
cout << "You can stand" << endl;
while(state==STAND){
state = (Movement)(1+rand()%4);}
}
}
}
In here, there are few rules. Lets call them as legal transitions
- From stand, he can walk or crawl
- From Walk, he can stand or run
- From Run, he can walk
- From Crawl, he can stand
So, here, if the legal transitions should be randomly selected. But, however, it should be according to the rules provided above. For an example, if “STAND” is selected, next thing to be selected should be “WALK” or “CRAWL” likewise. But as you can see here, all the result
2
You can walk
Why is that? Please help!
UPDATE:
Following code is with do..while loop, as suggested in a reply
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
enum Movement{STAND,WALK,RUN,CRAWL};
Movement state = (Movement)(1+rand()%4);
for(int i=0;i<10;i++)
{
cout << state;
if(state==STAND)
{
cout << " STAND is selected" << endl;
}
else if(state==WALK)
{
cout << " WALK is selected" << endl;
}
else if(state==RUN)
{
cout << " RUN is selected" << endl;
}
else if(state==CRAWL)
{
cout << " CRAWL is selected" << endl;
}
switch(state)
{
case STAND:
//cout << "You can walk or crawl" << endl;
do{state = (Movement)(rand()%4);}
while(state==WALK || state==CRAWL);
break;
case WALK:
//cout << "You can stand or run" << endl;
do{state = (Movement)(rand()%4);}
while(state==STAND || state==RUN);
break;
case RUN:
//cout << "You can walk" << endl;
do{state = (Movement)(rand()%4);}
while(state==WALK);
break;
default:
//cout << "You can stand" << endl;
do{state = (Movement)(rand()%4);}
while(state==STAND);
}
}
}
It is still the same. Now I get different answers, but not correct ones!!
Your logic is in the wrong order; your
whileloops will all be skipped because thestateis still what it was when you entered the particularcase. You might rewrite them withdo-whileto ensure they run at least once.