Random Generation

This is a discussion on Random Generation within the C++ Programming forums, part of the General Programming Boards category; Hi guys!
I'm writing a program that involves with random generation. Basically, I want to randomly generate a range of ...

Random Generation

Hi guys!

I'm writing a program that involves with random generation. Basically, I want to randomly generate a range of values, lets say from 1 to 10 to an array of 10 element. Another thing is I also want those generated values to not overlap each other like (1,2,2,3,3,4,5...) something like that. I want to guarantee that each value will only happen once in the array from a certain range.
I hope that u guys can give me a hand and help me with this, really appreciate that ^_^

The solution that you want is going to somehow break down to using an array (though, if the numbers only go from 1 -> 10, you could use an int.)

You'll want to save off that a number had been used and generate a new number until you find one that isn't used. That, or count up/down from your used position until you find some number that isn't used, the choice is up to you.

Start with an array of appropriate size and populated with the numbers 1,2,3...n and then randomize it by swapping, numerous times, random element a with random element b. You will thus avoid duplicates appearing. This will also allow you to insert duplicates at some later point if necessary.

thanks for the suggestion guys!
just a curious question, random_shuffle() does what? is it efficient to random a array?

Look here and especially the example.
Generally, it radnomizes the elements of a structure, like a std::vector.
It is efficient in general and it only lets you use random access iterators (thus you wouldn't be able to use a std::list, but a std::vector). Exactly how efficient I don't know, you will need to look at the implementation of the function.

It shuffles the elements in the specified range with uniform distribution. This range can be the entire range of an array, but as C_ntua noted, it must have random access to the range, and certainly pointers to the elements of an array qualify.

Originally Posted by davewang

is it efficient to random a array?

It is as efficient as what Fossaw described, if you interpret "numerous times" to be "one time less than the number of elements in the array". But it is better if you want a uniform distribution, and of course better in the sense that you do not have to code it yourself so you reduce the chance of introducing a bug.