Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random number picker between 2 numbers

I am working on a Tic-Tac-Toe game using C++ and I was wondering if it is possible to randomize a number but it could only choose either 2 or 5.

I made random start between user and the computer in order to make a fair start with these blocks of codes:

 srand(time(NULL));
 cout << "The First Person to go is randomly chosen!" << endl;
 FirsttoGo = (rand()%2) + 1;
 cout << "The first move goes to Player: " << FirsttoGo << endl;
 turn = FirsttoGo;

The feature that I would like to add is whoever starts the game will be able to pick either X or O but if the computer starts first, the computer should be able to pick between X or O. I also created constant values for X and O

static const int O = 5;
static const int X = 2;

Is there anyway to do this?

like image 252
tuygun Avatar asked Dec 18 '25 14:12

tuygun


2 Answers

In C++11 there are very nice and safer additions for the generation of random number in a range (see code below):

#include <random>
#include <iostream>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 2);
    for (int n=0; n<10; ++n) std::cout << dis(gen) << ' ';
    std::cout << '\n';
}

Furthermore, in this nice talk Stephan T. Lavavej illustrates the reasons why using rand() considered harmful.

Based on the above example you could adjust it for your problem like this:

int getRandomIDX(int const a = 5, int const b = 2) {
  std::random_device rd;
  std::mt19937 gen(rd());
  std::uniform_int_distribution<> dis(1, 2);
  return (dis(gen) == 1)? a : b;
}
like image 168
101010 Avatar answered Dec 21 '25 06:12

101010


(rand() > RAND_MAX/2) ? 2 : 5;
like image 37
BonzaiThePenguin Avatar answered Dec 21 '25 06:12

BonzaiThePenguin