Assigning 10 unique random numbers to an array

Hi, I am fairly new to C++ and would appreciate some help with this logic here. I need to create an array of 10 integers (1-10) but they should only appear once each time, so basically 1-10 in a random order.

I have some code so far (below) but I can't work out how to make sure each integer is unique.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <conio.h>
#include <time.h>

using namespace std;

int main()

{
	int NumArray[10];

	for (int i = 0; i < 10; i++)
	{NumArray[i] = rand () % 10;
	cout << NumArray[i] << endl;}
		
	_getch();
	return 0;
}


Any help or pointers towards this is appreciated, thanks for your time.
I see you #included <time.h> (which should be <ctime>, but details). I also see, however, that you're not using anything from it. Are you missing a srand() somewhere?

Here's what you can do. If you want 1-10 in a random order, then just assign {1,2,3,4,5,6,7,8,9,10} to your array and then write some sort of function to shuffle it.

Alternatively, if you want 10 unique integers that aren't necessarily 1-10, then as you generate each random integer, you can check to see if it already exists.

Whichever path you take, good luck!

-Albatross
Your example shows you want 10 random numbers [0,9] and your text says you want them to be unique. There's only one way to draw 10 random unique numbers from [0,9], so all that matters is the order in which they appear. This is called a permutation. The STL has a built-in version for it, called random_shuffle.

Your problem thus boils down to:
1
2
3
int myInts[10];
for (int i = 0; i < 10; ++i) myInts[i] = i; // Sets myInts to [0 ... 9]
random_shuffle(myInts, myInts+10);


You can also skip the generation step by using generate(_n), but these are a bit confusing to use.

http://www.cplusplus.com/reference/algorithm/random_shuffle/
http://www.cplusplus.com/reference/algorithm/generate_n/
http://www.cplusplus.com/reference/algorithm/generate/
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
#include <iostream>
#include <stdio.h>
#include <time.h>

using namespace std;

int main(int argc, char *argv[])
{
    int NumArray[10];

    for(int i=0;i<10;i++)
    {
again:
        srand((unsigned) time(0));

        NumArray[i]=1+(rand()%10);
        for(int y=0;y<10;y++)
        {
            if(NumArray[i]==NumArray[y]) goto again;
        }
    }

    for(int i=0;i<10;i++) cout<<"Random Number "<<i<<": "<<NumArray[i]<<endl;

    return 0;
}


this would be my solution... I don't know if it would match your intention.
FlashDrive,
Gotos are deprecated in both C and C++, and srand() should be called only once.

Furthermore, how does you giving a solution help the original poster in the long term? I have reason to believe that it doesn't...
http://cplusplus.com/articles/DjGEy60M/

-Albatross
To your 2nd aspect:

I'll explain it.

==========
THE INCLUDES
==========


I guess it's clear that you need #include <iostream> if you want to outputsomething on screen, e.g. text. #include <stdio.h> includes the implementation of rand()I guess..., so that you can use it as you want to. Because I used srand((unsigned) time(0)), I have had to include #include <time.h> . If I qould have not, the compiler would have complained about this.

==============
THE MAIN FUNCTION
==============


This is the heart of a program, programmed with C++. This int main(int argc, char *argv[]) is used if you debug the project where your main.cpp is in and you use so-called parameters.
As Albatross said, you should call srand((unsigned) time(0)) only once. So the source code of this file should look like at the end of this post. Using NumArray[i]=1+(rand()%10), you generate a semi-random number and store it in NumArray[i]. The essential thing is that you want to have each number only once. The
1
2
3
4
        for(int y=0;y<10;y++)
        {
            if(NumArray[i]==NumArray[y]) goto again;
        }
in lines 17 to 20 attends this. The goto again; makes the program to get back to the label (a 'word' with a colon behind it) named again:. So, if the number is the same as anotherone already saved in the array, the program will get back to again: and re-starts doing this random stuff, until the number/s which is/are needed is/are addicted. see EDIT, below
At last, the for(int i=0;i<10;i++) cout<<"Random nuber "<<i<<": "<<NumArray[i]<<endl; makes the program output for example this:
Random number 0: 5
Random number 1: 2
Random number 2: 7
Random number 3: 1
Random number 4: 4
Random number 5: 9
Random number 6: 6
Random number 7: 8
Random number 8: 3
Random number 9: 10

At the end of main() you need a return-statement because the return value of main() is int. If you would have a function void function() you do not need a return-statement.


The final 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
#include <iostream>
#include <stdio.h>
#include <time.h>

using namespace std;

int main(int argc, char *argv[])
{
    int NumArray[10];
    srand((unsigned) time(0));

    for(int i=0;i<10;i++)
    {
        NumArray[i]=1+(rand()%10);
        for(int y=0;y<10;y++)
        {
            if(NumArray[i]==NumArray[y])
            {
                i--;
                break;
            }
        }
    }

    for(int i=0;i<10;i++) cout<<"Random Number "<<i<<": "<<NumArray[i]<<endl;

    return 0;
}


EDIT: Sorry, please use instead of the goto again; a
1
2
{i--;
break;}
. It makes the same as the goto again; but you can't choose which label to go, becuse the for-loop is 'finished' and the program goes back to line 16.

HINT: If you use i++/y++/whatever++, it's the same as if you would code i=i+1/y=y+1/whatever=whatever+1. If you want to substract instead, use i-- or something equal. If you want to add/substract more than one, use i+=summand/i-=subtrahend
Last edited on
@FlashDrive
Like this.
14
15
16
17
18
19
20
21
22
23
        bool reloop = true;
        while(reloop) {
            NumArray[i]=1+(rand()%10);
            for(int y=0;y<10;y++) {
                if(NumArray[i]!=NumArray[y]) {
                    reloop = false;
                    break;
                }
            }
        }


The problem with goto is that it's a readability disaster and most of its uses in C++ have been replaced by more readable constructs. It's also not exactly the least error-prone statement in the book.

I (and many other regular members of this forum) still think giving out full solutions is bad idea.

-Albatross
Last edited on
but I explained it also... =(
#include <stdio.h> includes the implementation of rand()
rand() is declared in cstdlib
Headers may include others, but that is implementation defined.
When in doubt RTFM.

In Albatross's code the condition makes no sense.
And this is wrong for(int y=0;y<10;y++) (the loop for checking repeated values).

1
2
3
4
for(Iter K = begin; K!=end; ++K)
  do 
    *K = gen();
  while( exists(begin, K, *K) ); //range [) 

Last edited on
Topic archived. No new replies allowed.