# include # include # include using namespace std; int main ( ) // // RANDOM_WALK_2D puts a fly at the origin of a box whose walls are // 20 units away, and a spider at a random position. The spider and // the fly randomly walk around the box. The fly "wins" by stepping on // the spider. The spider wins by stepping on the fly. The fly escapes // by reaching one of the walls. // { int dist, step, x, x2, y, y2; int random_int ( int a, int b ); srand ( time ( 0 ) ); step = 0; x = 0; y = 0; x2 = random_int ( -10, 10 ); y2 = random_int ( -10, 10 ); dist = abs ( x - x2 ) + abs ( y - y2 ); // // Output initial position for GNUPLOT. // cout << " " << step << " " << x << " " << y << " " << x2 << " " << y2 << " " << dist << "\n"; while ( true ) { step = step + 1; x = x + random_int ( -1, +1 ); y = y + random_int ( -1, +1 ); // // Did we touch the spider? // if ( x == x2 && y == y2 ) { cerr << "Caught the spider on step " << step << "\n"; break; } // // Did we reach the wall? // if ( x == -20 || x == +20 || y == -20 || y == +20 ) { cerr << "Reached safety on step " << step << "\n"; break; } // // The spider moves. // x2 = x2 + random_int ( -1, +1 ); y2 = y2 + random_int ( -1, +1 ); // // The spider doesn't leave the box. // if ( x2 < -20 ) { x2 = -20; } if ( 20 < x2 ) { x2 = 20; } if ( y2 < -20 ) { y2 = -20; } if ( 20 < y2 ) { y2 = 20; } // // Did the spider eat the fly? // if ( x == x2 && y == y2 ) { cerr << "The spider caught the fly on step " << step << "\n"; break; } // // Compute distance. // The ABS() function is used for the absolute value of ints. // dist = abs ( x - x2 ) + abs ( y - y2 ); // // Output current status for GNUPLOT. // cout << " " << step << " " << x << " " << y << " " << x2 << " " << y2 << " " << dist << "\n"; } return 0; } int random_int ( int a, int b ) // // RANDOM_INT returns a random int between a and b. // { int range; int value; // // If we want integers between A and B, there are actually // B - A + 1 values. // range = b - a + 1; value = a + rand ( ) % range; return value; }