mercredi 20 mai 2020

Two VBA algorithms of Fisher-Yates Shuffle

  1. First algorithm

/

Dim i, j, temp, sizeArray As Integer
Dim tempCards(), shuffledCards() As Integer

sizeArray = 10

ReDim tempCards(1 To sizeArray)
ReDim shuffledCards(1 To sizeArray)

For i = 1 To sizeArray
    tempCards(i) = i
Next i

Randomize
Do While sizeArray >= 1
    j = Int(sizeArray * Rnd) + 1
    temp = temp + 1
    shuffledCards(temp) = tempCards(j)
    For i = j + 1 To sizeArray
        tempCards(i - 1) = tempCards(i)
    Next i
    sizeArray = sizeArray - 1
Loop
  1. Second algorithm

/

Dim i, j, temp, sizeArray As Integer
Dim tempCards(), shuffledCards() As Integer

sizeArray = 10

ReDim tempCards(1 To sizeArray)
ReDim shuffledCards(1 To sizeArray)

For i = 1 To sizeArray
    tempCards(i) = i
Next i

Randomize
For i = 1 To sizeArray
    temp = tempCards(i)
    j = Int((sizeArray + 1 - i) * Rnd) + i
    tempCards(i) = tempCards(j)
    tempCards(j) = temp
Next i

I made two algorithms and compared these. I think that first is the same with Fisher-Yates Shuffle, but that algorithm is not efficient, the worst.. so I made the second one, but I am not sure it is Fisher-Yates Shuffle logic.

Q) Is the second algorithm Fisher-Yates Shuffle? How about the logic? Let me know.




Aucun commentaire:

Enregistrer un commentaire