473,387 Members | 1,766 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

tortoise & hare

Hi everybody,

I have been getting so much good advice here that I figured I would
post another question. I am still learning c++ from a text that I
inherited from my brother. I am now working on a problem that seems
lame, but I really want it to work. It is a tortoise & hare sim. I
am pretty sure I have everything right except printing the array. I
cannot figure out how to print the array correctly. It should print
the T & H one after another depending on the calculated location. I
am having trouble understanding how to input data to the array and
then print it without printing the entire array. Here is my source so
far.

#include <iostream>
#include <ctime>

using std::cout;
using std::endl;

void moveTortoise( int *);
void moveHare( int * );
void printCurrentPositions( int *, int * );
void delay ( double );

char arrayRace[71] = {' '};

int main()
{

int hPos = 1; // hare's position
int tPos = 1; // tortoise's position

cout << "BANG !!!!!" << endl << "AND THEY\'RE OFF !!!!!" << endl;

srand(time(0));

while ( hPos < 70 && tPos < 70 ) {

moveTortoise( &tPos ); //works fine
delay (.2);
moveHare ( &hPos );
printCurrentPositions( &tPos, &hPos ); // problem here!

} // end while

if ( hPos > tPos )
cout << "\nHare wins. Yuch.";
else if ( hPos < tPos )
cout << "\nTORTOISE WINS!!! YAY!!!";
else if ( hPos == tPos )
cout << "\nIts a tie. Good job Tortoise!";

return 0;

} // end main

void moveTortoise( int *tPosptr )
{
int i = ( 1 + rand() % 10 );

if ( ( i >= 1 ) && ( i <= 5 ) )
*tPosptr += 3;
else if ( ( i >= 6 ) && ( i <= 7 ) )
*tPosptr -= 6;
else if ( ( i >= 8 ) && ( i <= 10 ) )
*tPosptr += 1;

if ( *tPosptr < 1 )
*tPosptr = 1;

} // end moveTortoise

void moveHare( int *hPosptr )
{
int j = ( 1 + rand() % 10 );

if ( ( j >= 1 ) && ( j <= 2 ) )
*hPosptr = *hPosptr;
else if ( ( j >= 3 ) && ( j <= 4 ) )
*hPosptr += 9;
else if ( j == 5 )
*hPosptr -= 12;
else if ( ( j >= 6 ) && ( j <= 8 ) )
*hPosptr += 1;
else if ( ( j >= 9 ) && ( j <= 10) )
*hPosptr -= 2;

if ( *hPosptr < 1 )
*hPosptr = 1;

} // end moveHare
void printCurrentPositions( int *tPosptr, int *hPosptr )
{
for ( int track = 1; track <= 70; track++ ) {

if ( track == *tPosptr ) {
arrayRace[track] = 'T';
}

if ( track == *hPosptr ) {
arrayRace[track] = 'H';
}

if ( track == *hPosptr == *tPosptr ) {
arrayRace[track] = 'O';
}

}

cout << arrayRace;

} // end printCurrentPositions

void delay( double how_long )
{
clock_t target = static_cast< clock_t >( how_long * CLOCKS_PER_SEC )
+ clock();
while ( clock() <= target )
{ } // Do Nothing
}

thanks in advance,

shock
Jul 19 '05 #1
4 4101

"Shock" <sh*****@charter.net> wrote in message news:ef**************************@posting.google.c om...
char arrayRace[71] = {' '};
There is no practical rason why this is global. It ought to be local
to the print function.
while ( hPos < 70 && tPos < 70 ) {
You use the constant 70 all over the place (and in the case above
70+1). Would be nice if this was all done in one place:

const int GamePositions = 70;

That way if you decide to change the value from 70 to 75 you
don't have to hunt down and change all the 70 and 71's to 75's and
76's. Also, it doesn't leave people wondering what this number means.
void printCurrentPositions( int *tPosptr, int *hPosptr )
Why do you pass in pointers here? You don't change the values, at the very
list they should be const pointers, but passing just the int's value would make more sense. {
for ( int track = 1; track <= 70; track++ ) {

if ( track == *tPosptr ) {
arrayRace[track] = 'T';
}

if ( track == *hPosptr ) {
arrayRace[track] = 'H';
}

if ( track == *hPosptr == *tPosptr ) {
arrayRace[track] = 'O';
}

cout << arrayRace;


cout here gets a const char* which refers to the first element of arrayRace. This is expected
to be the first element of a null-terminated array. In your case you have not terminated the array.
You could bump up the size to 72, and then set arrayRace[71] to his value before you
call cout. However, there's no need to maintain an array here at all.

void printCurrentPositions(int tPos, in hPos) {
for(int pos = 1; pos <= 70; ++pos) {
if(track == tPos) cout << 'T';
else if(track = hPos) cout << 'H'; // what if tPos == hPos?
else cout << ' ';
}
cout << '\n';
}
Jul 19 '05 #2
//Hi everybody,
//
//I have been getting so much good advice here that I figured I would
//post another question. I am still learning c++ from a text that I
//inherited from my brother. I am now working on a problem that seems
//lame, but I really want it to work. It is a tortoise & hare sim. I
//am pretty sure I have everything right except printing the array. I
//cannot figure out how to print the array correctly. It should print
//the T & H one after another depending on the calculated location. I
//am having trouble understanding how to input data to the array and
//then print it without printing the entire array. Here is my source so
//far.

Hi Shock,

I messed up the code a bit, but there still is a problem. When Hare
wins, the message for Tortoise is displayed, and vice versa. You'll
hate the 'tightcode' that I use, but I am afraid the language will
overload tab and space in the near future, so I leave them out. I
wished that your brother could hack this, too.

-X

#include <iostream.h>
#include <string>
#include <stdlib.h>
#include <ctime>
struct Runner
{
enum{PARCOURS=70};
int pos;
Runner():pos(1){}
bool finished(){return pos==PARCOURS;}
virtual int jump(int)=0;
operator int(){return pos;}
void move()
{
pos+=jump(rand()%10+1);
pos=pos<1?1:pos>PARCOURS?PARCOURS:pos;
}};
struct Hare:Runner
{
int jump(int a)
{
bool b=a>=1&&a<=2;
bool c=a>=3&&a<=4;
bool d=a==5;
bool e=a>=6&&a<=8;
bool f=a>=9&&a<=10;
return b?0:c?9:d?-12:e?1:f?-2:0;
}};
struct Tortoise:Runner
{
int jump(int a)
{
bool b=a>=1&&a<=5;
bool c=a>=6&&a<=7;
bool d=a>=8&&a<=10;
return b?3:c?-6:d?1:0;
}};
bool operator==(const Runner&a,const Runner&b){return a.pos==b.pos;}
bool operator<(const Runner&a,const Runner&b){return a.pos<b.pos;}
void print(const Runner&a,Runner&b)
{
string c(71,' ');
c[70]='|';
c[a]='T';
c[b]='H';
if(a==b)c[a]='O';
cout<<c<<endl;
}
void delay(double a)
{
clock_t b=static_cast<clock_t>(clock()+a*CLOCKS_PER_SEC);
while(b>clock()){} // Do Nothing
}
int main()
{
Hare hare;
Tortoise tortoise;
string harewins="\nHare wins. Yuch.";
string tortoisewins="\nTORTOISE WINS!!! YAY!!!";
string tie="\nIts a tie. Good job Tortoise!";
srand(time(0));
cout<<"BANG !!!!!\nAND THEY\'RE OFF !!!!!i\n";
print(hare,tortoise);
while(!hare.finished()&&!tortoise.finished())
{
tortoise.move();
delay(.02);
hare.move();
print(hare,tortoise);
}
cout<<(hare==tortoise?tie:hare<tortoise?tortoisewi ns:harewins); //??
return 0;
}

Jul 19 '05 #3
"Agent Mulder" <mb*******************@home.nl> wrote in message news:<bk**********@news3.tilbu1.nb.home.nl>...
//Hi everybody,
//
//I have been getting so much good advice here that I figured I would
//post another question. I am still learning c++ from a text that I
//inherited from my brother. I am now working on a problem that seems
//lame, but I really want it to work. It is a tortoise & hare sim. I
//am pretty sure I have everything right except printing the array. I
//cannot figure out how to print the array correctly. It should print
//the T & H one after another depending on the calculated location. I
//am having trouble understanding how to input data to the array and
//then print it without printing the entire array. Here is my source so
//far.

Hi Shock,

I messed up the code a bit, but there still is a problem. When Hare
wins, the message for Tortoise is displayed, and vice versa. You'll
hate the 'tightcode' that I use, but I am afraid the language will
overload tab and space in the near future, so I leave them out. I
wished that your brother could hack this, too.

-X

#include <iostream.h>
#include <string>
#include <stdlib.h>
#include <ctime>
struct Runner
{
enum{PARCOURS=70};
int pos;
Runner():pos(1){}
bool finished(){return pos==PARCOURS;}
virtual int jump(int)=0;
operator int(){return pos;}
void move()
{
pos+=jump(rand()%10+1);
pos=pos<1?1:pos>PARCOURS?PARCOURS:pos;
}};
struct Hare:Runner
{
int jump(int a)
{
bool b=a>=1&&a<=2;
bool c=a>=3&&a<=4;
bool d=a==5;
bool e=a>=6&&a<=8;
bool f=a>=9&&a<=10;
return b?0:c?9:d?-12:e?1:f?-2:0;
}};
struct Tortoise:Runner
{
int jump(int a)
{
bool b=a>=1&&a<=5;
bool c=a>=6&&a<=7;
bool d=a>=8&&a<=10;
return b?3:c?-6:d?1:0;
}};
bool operator==(const Runner&a,const Runner&b){return a.pos==b.pos;}
bool operator<(const Runner&a,const Runner&b){return a.pos<b.pos;}
void print(const Runner&a,Runner&b)
{
string c(71,' ');
c[70]='|';
c[a]='T';
c[b]='H';
if(a==b)c[a]='O';
cout<<c<<endl;
}
void delay(double a)
{
clock_t b=static_cast<clock_t>(clock()+a*CLOCKS_PER_SEC);
while(b>clock()){} // Do Nothing
}
int main()
{
Hare hare;
Tortoise tortoise;
string harewins="\nHare wins. Yuch.";
string tortoisewins="\nTORTOISE WINS!!! YAY!!!";
string tie="\nIts a tie. Good job Tortoise!";
srand(time(0));
cout<<"BANG !!!!!\nAND THEY\'RE OFF !!!!!i\n";
print(hare,tortoise);
while(!hare.finished()&&!tortoise.finished())
{
tortoise.move();
delay(.02);
hare.move();
print(hare,tortoise);
}
cout<<(hare==tortoise?tie:hare<tortoise?tortoisewi ns:harewins); //??
return 0;
}


I am a rookie, and you code is complex. Here is what I came up with
for my print positions module.

char array[GamePos];

for ( int i = 0; i < GamePos; i++ ) {
array[i] = ' ';
array[GamePos] = '\0';

if ( hPos == tPos ) {
array[tPos] = 'O';
array[tPos] = 'U';
array[tPos] = 'C';
array[tPos] = 'H';
array[tPos] = '!';
array[tPos] = '!';
array[tPos] = '!';
}
else {
array[tPos] = 'T';
array[hPos] = 'H';
}

cout << array << endl;

It works. Thanks for the tips everybody!

shock56
Jul 19 '05 #4
Shock wrote:


I am a rookie, and you code is complex. Here is what I came up with
for my print positions module.

char array[GamePos];
You may want:
char array[GamePos + 1];
to allow for the terminating null character ('\0').


for ( int i = 0; i < GamePos; i++ ) {
array[i] = ' ';
array[GamePos] = '\0';
Note that array[GamePos] is one past the end of the array.
The assignment will cause Undefined Behavior. Search
news.comp.lang.c for "Nasal Demons".

Change your array to be larger by one.


if ( hPos == tPos ) {
array[tPos] = 'O';
array[tPos] = 'U';
array[tPos] = 'C';
array[tPos] = 'H';
array[tPos] = '!';
array[tPos] = '!';
array[tPos] = '!';
This is really interesting. The index to the array doesn't
change, so the same character in the array gets changed many
times.

Try these:
if (hPos == tPos)
{
strcpy(array + tPos, "OUCH!!!");
// OR
array[tPos++] = 'O';
array[tPos++] = 'U';
// etc.
// OR
array[++tPos] = 'O';
array[++tPos] = 'U';
// etc.
}
}
else {
array[tPos] = 'T';
array[hPos] = 'H';
}

cout << array << endl;

It works. Thanks for the tips everybody!


Not all the time. There are cases where data is written past
the end of the array. For example, when tPos == hPos == GamePos,
in the above "if" statment, the phrase "OUCH!!!" will be written
past the end of the array, promoting undefined behavior.
--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book

Jul 19 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Eric | last post by:
Greetings Comrades, Pythonistas! I am looking for guidance on the quick and easiest path to set up a Python wiki. A wiki application idea popped into my head while I was making morning coffee. ...
1
by: DrTebi | last post by:
Hello, I have the following problem: I used to "encode" my email address within links, in order to avoid (most) email spiders. So I had a link like this: <a...
81
by: Michael Rozdoba | last post by:
I've been wandering around the results of numerous googles for several hours without reaching a conclusive solution, so I'm dipping a tentative toe back in ciwah... I've been persuaded here in...
10
by: Vince | last post by:
The following is code for the classic tortoise and hare C assignment. I am posting this for educational purposes only. Please do not plagiarize as comp sci instructors regularly read newsgroups....
3
by: Bob E | last post by:
How can I insert a field name like O'Hare or O'Conner into a table. I would rather not have to check every field entered to see if the character ( ' ) is in the field. I'm entering Streets, Names,...
2
by: FUGATO | last post by:
How I can design a Hare and tortoise using pointer? Somebody can give an idea about that.
14
by: Arne | last post by:
A lot of Firefox users I know, says they have problems with validation where the ampersand sign has to be written as &amp; to be valid. I don't have Firefox my self and don't wont to install it only...
0
by: Buckaroo Banzai | last post by:
Hello, newbie here... I'm writing this program but when I click the start button which should initiate either the Hare or the Tortoise, it does not, this is the first time I use threads, so the...
2
by: sandeep | last post by:
hi we are using tortoise cvs and putty. i want to write a python script to whom i can provide a tag and module.now what this script will do is look for this specific tag and checks for whether...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.