goombaloon
goombaloon

Reputation: 3099

How To Generate A Unique 4-Digit String

I'm looking for a way to generate a (fairly) unique (non auto-incrementing) 4-digit string using the numbers 0 - 9 for each digit using C#. I can validate uniqueness and generate another number if a dup is found. I had thought about basing the number somehow on the DateTime object's Ticks property but am having a difficult time putting the pieces together.

Any thoughts or expertise would be much appreciated.

Upvotes: 3

Views: 9865

Answers (5)

ojrac
ojrac

Reputation: 13421

Depends on your requirements. How many of these do you expect to generate? If you just need a couple hundred, you can generate a random number 0 to 9999. If you expect to generate all 10,000 of them, then you should just do something like Earwicker said, and maintain a list of all the unused values.

I'd suggest that you start with the simplest algorithm (pick a random number 1 to 9999), and use it until it's too slow. Then go back and put in Earwicker's.

Upvotes: 0

Daniel Earwicker
Daniel Earwicker

Reputation: 116654

Create an array of all 10000 values, using the short type, and then shuffle it.

Upvotes: 1

bdukes
bdukes

Reputation: 155895

Random randomNumberGenerator = new Random();
return string.Concat(
    randomNumberGenerator.Next(0, 9),
    randomNumberGenerator.Next(0, 9),
    randomNumberGenerator.Next(0, 9),
    randomNumberGenerator.Next(0, 9));

Upvotes: -3

mqp
mqp

Reputation: 71937

If it doesn't increment itself, how is it going to be unique the second time?

Is what you're saying that you want to generate a random 4-digit string from the set of all possible unused 4-digit strings?

If so, the correct approach is usually to generate all possible 4-digit strings, and shuffle them into a random order. Then take them in order as you need new ones.

CLARIFICATION: Other answers suggest simply generating a random 4-digit string and leaving it at that. Presumably you would then check to see whether it was already used, and generate another one if it's used. This has the potential of having extremely suboptimal performance. Suppose you have already used 9,999 (all but one) of the possible 4-digit strings ranging from 0000 to 9999. To generate the last one, this method may take many, many tries.

Upvotes: 9

TheTXI
TheTXI

Reputation: 37875

Generate four random numbers each from 0-9 and then do string concatenation on them.

Upvotes: -1

Related Questions