How to generate random numbers using only specific

2019-08-11 00:46发布

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?

3条回答
beautiful°
2楼-- · 2019-08-11 01:03

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.

Sub Main()
    Dim min As Integer = 1
    Dim max As Integer = 4

    Dim length As Integer = 4


    Dim ranNumFinal As String = ""

    Static generator As System.Random = New System.Random()

    For i = 1 To length
        If i = 1 Then 'First time around
            ranNumFinal = generator.Next(min, max + 1).ToString
        Else
            ranNumFinal = ranNumFinal.ToString & generator.Next(min, max + 1).ToString
        End If
    Next
    Console.WriteLine(ranNumFinal)
    Console.Read()
End Sub
查看更多
forever°为你锁心
3楼-- · 2019-08-11 01:08

Here you go.

    Dim r As New Random
    For i As Integer = 1 To 10
        Debug.WriteLine(r.Next(1, 5) * 1000 + r.Next(1, 5) * 100 + r.Next(1, 5) * 10 + r.Next(1, 5))

    Next
查看更多
闹够了就滚
4楼-- · 2019-08-11 01:19

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 want N values made from those four digits, using each one once. The starting point this Permutation 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).

Dim Combos = Permutation.Create("1234".ToCharArray())

Dim intVals = Combos.ConvertAll(Of Int32)(Function(s) Int32.Parse(s)).
            OrderBy(Function(r) RNG.Next()).
            ToArray()
  • The first part gets the combination of 24 element, then
  • converts the result to integer
  • then randomizes the order and puts it in an array.

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) after OrderBy 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:

查看更多
登录 后发表回答