How to ensure random int are unique in Bulls and cows?

Here is a segment :
1
2
3
4
5
6
7
8
9
 
void fill_ans()
{
	for (int i = 0; i < digit_size; ++i)
		ans.push_back( rand() % 9 + 1) ; // a random integer belonging to [1,9]
	//for (int i = 0; i < digit_size; ++i)
	//	cout << ans[i]; 		
}

The program works but sometimes the four digits are not unique. How do I ensure that?
Last edited on
Random numbers and unique numbers are two different things. The easiest way to get unique numbers is to fill a vector with the numbers in the range and shuffle it. Then you can just loop through the vector.
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
#include <iostream>
#include <random>
#include <ctime>
#include <algorithm>
#include <iterator>

int main()
{
    // initialise thje random number engine
    // http://en.cppreference.com/w/cpp/numeric/random
    std::mt19937 rng( std::time(nullptr) ) ;

    int digits[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;

    const std::size_t ANS_SIZE = 4 ; // invariant: ANS_SIZE <= 10
    int answer[ANS_SIZE] ;

    for( int i = 0 ; i < 20 ; ++i )
    {
        // shuffle the digits like shuffling a pack of cards
        // http://en.cppreference.com/w/cpp/algorithm/random_shuffle
        std::shuffle( std::begin(digits), std::end(digits), rng ) ;
        
        // copy the first ANS_SIZE digits into the answer
        // http://en.cppreference.com/w/cpp/algorithm/copy
        // http://en.cppreference.com/w/cpp/iterator/begin
        std::copy( std::begin(digits), std::begin(digits) + ANS_SIZE, answer ) ;

        // http://www.stroustrup.com/C++11FAQ.html#for
        for( int d : answer ) std::cout << d ;
        std::cout << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/42abffd3e0cff394
Thanks a lot, both of you!
Topic archived. No new replies allowed.