generating random numbers in an array without repetition

Hi,I was trying to generate random numbers to fill in an array but my code seems to not work.

Here's my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
   int n,m,num;
    cout<<"num"<<endl;
    cin>>num;
    cout<<"n"<<endl;
    cin>>n;
    cout<<" m"<<endl;
    cin>>m;
    int arr[n][m];
    srand(time(NULL));

    for(int i=0; i<n; i++)
    {
        for(int j=0; j<m; j++)
        {
            arr[i][j]=rand()%(2*num+1)-num;
            cout<<arr[i][j]<<" ";

        }
        cout<<endl;
    }
    cout<<endl;
bool replacem=false;
int cont=0;
    do
    {  


        for(int i=0; i<n; i++)
        {
            for(int j=0; j<m; j++)
            {
                 replacem=false;
                for(int x=0; x<n; x++)
                {
                    for(int y=0; y<m; y++)
                    {
                        if(arr[x][y]==arr[i][j])
                        { cont++;
                            if(cont>1){
                            arr[x][y]=rand()%(2*num+1)-num;
                            replacem=true;
                            }
                            else replacem=false;
                        }

                    }
                }

            }
        }
    }
    while(replacem==true);
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<m; j++)
        {

            cout<<arr[i][j]<<" ";

        }
        cout<<endl;
    }


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <set>
#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;
int main()
{

  set<int> alreadyUsedNumbers;
  const int n = 4;
  const int m = 5;
  int arr[n][m];  // THIS IS ILLEGAL C++ IF n AND m ARE NOT CONSTANTS. AS IN YOUR CODE. YOUR CODE IS BAD.
  srand(time(NULL));

  for (int i = 0; i<n*m; ++i)
    {
      int number = rand();
      while (alreadyUsedNumbers.find(number) != alreadyUsedNumbers.end())
	{
	  number = rand();
	}
      arr[0][i] = number;
      alreadyUsedNumbers.insert(number);
    }
}

Last edited on
Topic archived. No new replies allowed.