I’m working on a .NET application in C# that will generate a variable-length string of random digits. I’d like to add a checklist that will allow the user to select any combination of digits between zero and nine and prevent them from appearing in the string. Currently, I simply do this to get the string:
do
{
int num = rnd.Next(10);
output += num.ToString();
i++;
}
while (i < stringLength);
I can think of a way to exclude selected digits by throwing them out once they are generated and not incrementing the counter, but it seems like there would be a less wasteful algorithm. The program will support generating a number of strings, so if a user is creating millions of strings, I’d like to keep overhead at a minimum.
Bonus: I forgot to mention that I’d also like if someone could point me to a resource for patterns such as this. I’ll be working a lot with random numbers based on parameters in the near future and I’d like to learn some principles instead of asking questions about individual problems such as this.
If you generate an array of allowed characters then pick from that:
obviously
allowedDigitsis generated rather than hard coded 😉Using a
StringBuilderis more efficient and you don’t have to explicitly do theToString.