Randomizing an array

前端 未结 3 1654
栀梦
栀梦 2021-01-22 07:57

I wish to implement the Dr.D.E.Knuth\'s Subtractive RANDOM number generation algorithm. I wish to implement an ATM panel on which when very time user log-in the buttons will be

相关标签:
3条回答
  • 2021-01-22 08:41

    To set the position of the buttons randomly in the panel, instead of using n from 0 to 9 in the loop, you can use a random value from 0 to 9. Be sure you don't use the same value twice.

    0 讨论(0)
  • 2021-01-22 08:48

    You don't need to use a cryptographically secure random number generator for that, nor do you need a separate class.

    Private Shared rng As New Random()
    
    Private Shared Function ShuffleArray(Of T)(arr() As T) As T()
        Dim left = Enumerable.Range(0, arr.Length).ToList()
        Dim result(arr.Length - 1) As T
    
        For i = 0 To arr.Length - 1
            Dim nextIndex = rng.Next(left.Count)
            result(i) = arr(left(nextIndex))
            left.RemoveAt(nextIndex)
        Next
    
        Return result
    End Function
    
    0 讨论(0)
  • 2021-01-22 08:50

    There are quite some "shuffle" algorithms (search Fisher-Yates for example) and they are usually not difficult to implement. The EASIEST (imho) way, ist to use LINQ:

    Dim r As New Random
    Dim out = (From b In btnArray Order By r.Next Select b).ToArray
    

    Maybe the question is not clear: Do you want to shuffle the POSITIONS of the buttons or do you want to shuffle the CONTENT (buttons) of the Array?

    0 讨论(0)
提交回复
热议问题