tags:

views:

62

answers:

2

Is this code a good solution to randomise a two-dimensional array and write out all the symbols on the screen? If you have a better tip or solution please tell me.

 int slumpnr;
 srand( time(0) );
 char game[3][3] = {{'O','X','A'}, {'X','A','X'}, {'A','O','O'}};

 for(int i = 0 ; i < 5 ; i++)
 {
 slumpnr = rand()%3;
 if(slumpnr == 1)
 {
 cout << " " <<game[0][0] << " | " << game[0][1] << " | " << game[0][2] << "\n";
 cout << "___|___|___\n";
 }
 else if(slumpnr == 0)
 {
 cout << " " << game[1][0] << " | " << game[1][1] << " | " << game[1][2] << "\n";
 cout << "___|___|___\n";
 }
 else if(slumpnr == 3)
 {
 cout << " " << game[2][0] << " | " << game[2][1] << " | " << game[2][2] << "\n";
 cout << "___|___|___\n";
 }
 }
 system("pause");
 }
A: 

Except the last if that should be:

if(slumpnr == 2)   // 2 instead of 3

Everything looks ok. You are correctly initializing random sequence (take care to do it once only at startup), so you should get best random a computer can do.

Benoit Thiery
Not quite the best. On a 16-bit machine for instance, `(rand()%3)` is slightly biased towards returning a `0`. This bias is only about 0.005%, though!
Oli Charlesworth
+2  A: 

You don't need the if/else chain. Simply use the random variable as an index into your array:

int r = rand() % 3;
cout << " " <<game[r][0] << " | " << game[r][1] << " | " << game[r][2] << "\n";
cout << "___|___|___\n";

Oh, I just noticed you have a weird mapping from 1 to 0 and from 0 to 1. If that is really necessary (for whatever reason), I would implement it like this:

static const int mapping[] = {1, 0, 2};
int r = mapping[rand() % 3];
cout << " " <<game[r][0] << " | " << game[r][1] << " | " << game[r][2] << "\n";
cout << "___|___|___\n";

And no, I do not have MSN or something, but here is a complete program to get you going.

#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
    srand(time(0));
    char game[3][3] = {{'O','X','A'}, {'X','A','X'}, {'A','O','O'}};

    for (int i = 0; i < 5; ++i)
    {
        int r = rand() % 3;
        std::cout << " " <<game[r][0] << " | " << game[r][1] << " | " << game[r][2] << "\n";
        std::cout << "___|___|___\n";
    }
    system("pause");
}

Note however that this is not very random since you only pick from three different possible lines.

FredOverflow
Can you help me to get that code into my code?? Because I dont understand how to put into mine functions.
Atb
do you have msn or something? because i really need to finish my code and I suck on c++ :/
Atb
ok thank you so much for helping me out. Im really thankfull!
Atb
@Nelly: Note that I like [this answer](http://stackoverflow.com/questions/4003558/i-need-help-with-my-slot-machine-game/4003581#4003581) much better...
FredOverflow