-1

I am asked to create a unique (no two numbers are the same) set of random numbers (the user inputs the row and column dimensions 'd1' and 'd2')

I am totally lost as to how to compare each element of both arrays to see if they're duplicates.

(Max is the largest value to be generated)

    void RandomArray(IntArrayPtr* m, int d1, int d2, int max)
 {
for (int i = 0; i < d1; i++)
{
    for (int j = 0; j < d2; j++)
    {
        m[i][j] = (rand() % max + 1);
        if (i > 0 && j > 0)
        {
            if (m[i][j] == m[i][j - 1] || m[i][j] == m[i-1][j])
            {
                m[i][j] = (rand() % max+ 1);
            }
        }
    }
  }
}

2 Answers2

3

Store every value in C++ datastructure called unordered_set and check if the random value generated exists in this set or not.

Reference on how to use unordered_set: https://stackoverflow.com/a/24644253/3326925

PS: I'm not that good in C++ but can tell you to relate this with HashSet used in Java.

Community
  • 1
  • 1
Shrikant Kakani
  • 1,511
  • 2
  • 17
  • 37
0

Another solution is generating a set of n random numbers, using something like numbers.add( n + random() ) where n is the last number added and random() is a random increment (different each time).

Once you have the set, you can use std::random_shuffle(...)on it. And add the elements 1 by 1 on the matrix.

Ediolot
  • 501
  • 2
  • 6
  • 19