In VB.NET I am trying to figure out how exactly to generate numbers of a fixed length using specific digits.
I have seen these questions but they do not cover what I am looking for:
How do I generate random integers within a specific range in Java?
Produce a random number in a range using C#
How to generate random number with the specific length in python
Generating an array of random strings
Generation 9 digits random number including leading zero
I am trying to generate 4 digit numbers using only 1, 2, 3, and 4.
It would be like this:
1234
2134
3124
2143
2431
2413
etc...
Can someone explain to me how this can be achieved?
This will generate a number using the min and max (1 - 4) provided of the length provided (4) as a String. If you need to use the Integer, of course, you'll have to do that casting after it's generated. There could also be something funky that happens if the min < 0 and max > 9, of course.
Here you go.
As the comments note, the post leaves open several questions. As it stands there is not really much to do with
Random
. It sounds like you wantN
values made from those four digits, using each one once. The starting point thisPermutation
class from a great answer by Bjørn-Roger Kringsjå to create a list of the combinations of the digits (be sure to upvote it).If you didn't mean "values" but strings (referring to values having a length sounds more like strings of numerals), just skip the
ConvertAll
step. If you only need a few, you can add.Take(5)
afterOrderBy
to grab only 5 (for example).Personally, since there are only 24 possible (non repeating) combinations, I'd paste them into the code as an array and use that as the starting point unless the "1234" part is dynamic.
See also: