I'd like to generate a random number with each digit being in range from 0-9 and not repeating itself. Assume finite length of 4.
- 1234 qualifies, each composite digit is unique.
- 1123 does not, 1 is repeated
How can this be done please?
I'd like to generate a random number with each digit being in range from 0-9 and not repeating itself. Assume finite length of 4.
How can this be done please?
To generate the digits:
And to join the digits into a single number:
If you'd rather avoid needless use of std::vector and the memory allocations it brings, excessive randomisation calls presumably used within random_shuffle, there's a simpler approach if you play with some math.
If you can count how many valid (i.e. acceptable) sequences exist, C, and you can devise a bijective function that maps from this counter to each valid sequence instance then things become trivial. Generate a random integer in the range [0,C), plug that into your function which returns the valid output.
If I understand your example correctly, you want to generate a random 4 digit sequence ABCD (representing an integer in the range [0,9999]) where digits A, B, C and D are different from one another.
There are 5040 such valid sequences: 10 * 9 * 8 * 7.
Given any integer in the range [0, 5039], the following function will return a valid sequence (i.e. one in which each digit is unique), represented as an integer:
E.g.
I believe you are talking about generating permutations.
Try something like this:
Not the most efficient... It simply tracks what digits have been used, and rerolls any time a used digit is encountered.
The above does have the side-effect that zero is technically not used if it's the first number chosen. You could explicitly prevent this, or simply accept that some numbers will be 9 digits long.