0

So I'm trying to look for a very efficient way to generate number from a range. Basically, I am writing a code for a Tic Tac Toe between computer vs computer. I want to make sure the computer mark X/O randomly in a 2D array. A random point will be array[random][random].

For example, I want to make a move on a TicTacToe size 3x3

I use:

int range = 3;
int random = rand() % range + 1; 

The random number I got is only 3 after hundreds of time, which leads to invalid moves on the game.

I'm wondering if you can give me an idea how to generate a very linearly random integer between a small range. Thanks a lot!

  • 1
    Did you do `std::srand(std::time(nullptr))` before this code? – David G Sep 11 '18 at 00:55
  • *"The random number I got is only 3 after hundreds of time"* - care to elaborate on that statement. Are you saying you achieved `3` only once out of hundreds of the aforementioned lines of code? If so, include an **entire**, short program that does this (should be no more than a dozen lines and have both `#include` file set, and full `main()`. That btw, is a [mcve], and will *significantly* raise the quality of this question. Also, [``](https://en.cppreference.com/w/cpp/numeric/random) is the cat's whiskers for modern C++ programs. [Worth looking in to](https://ideone.com/BwrqSA). – WhozCraig Sep 11 '18 at 00:57

1 Answers1

1

Not entirely sure what you mean by "very linearly random," but if your array is 3x3, I believe you'd want to use

const int range = 3;
int random = rand( ) % range; // Get random index [0 - 2]

to generate valid indexes for your 3x3 array.

Alternatively, if your board is restricted to 3x3 you could just create a pre-defined std::vector of std::pair pairs - then use std::(random_)shuffle on the vector at the start of each game. This would avoid generating random coordinates for spaces that have already been played. However, this approach wouldn't scale well with larger boards.

Example vector:

std::vector<std::pair<size_t, size_t>> coords
{
    std::pair<size_t, size_t>(0, 0),
    std::pair<size_t, size_t>(0, 1),
    std::pair<size_t, size_t>(0, 2),
    std::pair<size_t, size_t>(1, 0),
    // ...
    std::pair<size_t, size_t>(2, 2)
};

See How to shuffle a std::vector for a quick example on how to shuffle the vector.

tferguson7337
  • 19
  • 1
  • 4