Assigning individual numbers from an array using rand() (i.e. no repeats)

Each time through my loop I want to assign number1, number2, number3 and number 4 a random number from the array numbers[]. However, I don't want to repeat any of the values of the array.
If I'm not being clear: If the numbers in the array were 5, 66, 3.9 and 23, I wouldn't want number1 and number3 both holding numbers[2].
I can't test to see if one variable holds the same number as another variable because two numbers in the array may be the same.
I cant test for example if number1 holds number[2] and then exclude number[2] from the others, unless you can exclude certain ranges from random numbers? And even if you could, that would still be a hell of a lot of if statements.

1
2
3
4
number1 = numbers[rand() % 4];
number2 = numbers[rand() % 4];
number3 = numbers[rand() % 4];
number4 = numbers[rand() % 4];


Any help would be awesome :)
How about something like this?

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
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
    srand(time(0));

    double numbers[4] = { 1.1, 2.2, 3.3, 4.4 };

    double n1, n2, n3, n4;

    int indexes[4] = { 0, 1, 2, 3 };

    random_shuffle(indexes, indexes + 4);

    n1 = numbers[indexes[0]];
    n2 = numbers[indexes[1]];
    n3 = numbers[indexes[2]];
    n4 = numbers[indexes[3]];

    cout
        << n1 << " " << n2 << " "
        << n3 << " " << n4 << endl;

    return 0;
}

Useful link -> http://cplusplus.com/reference/algorithm/random_shuffle/
That works perfectly. Thank you so much. This will definitely come in handy in future programs too.
Just one question though. The parameters you give random_shuffle. Looking at that, is random_shuffle always for arrays? And I take it saying indexes as a parameter in random_shuffle is the same as indexes[0]?
(1) Since indexes is an array, its name is a pointer to its first element. Also, since its
size is 4, indexes + 4 is a pointer to the element past the last element of the array.

(2) The random_shuffle function takes a [first, last) range as its
argument, specified by providing two random access iterators.

(3) A pointer is a random access iterator (the inverse is not necessarily true, though).

That's why I can write this -> random_shuffle(indexes, indexes + 4); and it works.

Useful links -> [ http://cplusplus.com/forum/general/45819/#msg248689 | http://cplusplus.com/reference/std/iterator/ ]
Topic archived. No new replies allowed.