### how do i stop rand to stop making duplicates

how do i stop rand to making any duplicates

 ``123456789101112131415`` `````` main () { int a; for (int i = 0; i <10; i++) { a = rand() % 10 + 1; cout << a << endl; } system ("pause"); } ``````

here was the output
2
8
5
1
10
5
9
9
3
5
Press any key to continue . . .
Last edited on
Hi there,

You could store the results of rand() in an array.
Every time you create a new random number, check whether or not it is already in the array.

This tutorial contains all the examples that you need to do so:
http://www.cplusplus.com/doc/tutorial/arrays/

Please do let us know if you require any further help.

All the best,
NwN
ooooh! Thank you NwN!!
If you're allowed to, I highly recommend learning how to use std::set, which will act like an array but prevent duplicate values automatically for you. It is also generally more efficient than using an array.
Last edited on
Thanks for the tip, LB!
Okay, so I tried making an array. no luck! :((
Can anyone give me an idea on how to do it? Lol

I also tried reading what LB told me and i cant understand a thing -_-
Here's one way. After generating each value, store it in an array.
When generating subsequent values, search through the previously-used values.If you find it, try again.
 ``12345678910111213141516171819202122232425`` `````` int arr[10]; // Array to hold up to 10 values for (int i=0; i<10; i++) { int r; bool found = true; while (found) { found = false; // begin by assuming the value is not found r = rand() % 10 + 1; // the random number for (int j=0; j

Here's another way. Store our wanted values in an array.
The first time we can select any value from the entire array.
Then replace the used value with the last item in the array. Next time, select from just the first nine items, then from the first eight and so on.
 ``12345678`` `````` int arr[10] = {1,2,3,4,5,6,7,8,9,10}; for (int size=9; size>=0; size--) { int ix = rand() % (size+1); // select an item from 0 to size cout << arr[ix] << " "; // output it arr[ix] = arr[size]; // replace the selected item with item[size] } ``````
Last edited on
here's another method.

 ``123456789101112131415`` ``````#include #include #include int generate( void ){ static int x = 0; return( ++x ); } int main() { std::vector numbers( 10 ); std::generate( numbers.begin() , numbers.end() , generate ); std::random_shuffle( numbers.begin() , numbers.end() ); for( const auto &it : numbers ) std::cout << it << ' '; }``````

It will generate numbers 1 - 10 then put them in a random order then output them.
Thanks alot chervil and giblit!

Btw, where can i fine a good tutorial on using vector? Im really not that familiar with vectors
Last edited on
Its an stl container kind of similar to an array. http://www.cplusplus.com/reference/vector/vector/
http://www.learncpp.com/ -- check out chapter 16 STL containers
Topic archived. No new replies allowed.