MyBB Community Forums

Full Version: Fisher Yates Shuffle in Visual Basic?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey guys,

I'm still new to Visual Basic, and I just completed a Memory game. Big Grin The only problem is that the values of the cards never change, since they are in a static array.

I've heard of a Fisher Yates shuffle that should do exactly what I want (randomize my fixed list), however I don't know how to implement it.

Here's what I have to assign values:

Cards(0) = 60
Cards(1) = 37
Cards(2) = 84
Cards(3) = 23
Cards(4) = 19
Cards(5) = 95
Cards(6) = 37
Cards(7) = 60
Cards(8) = 84
Cards(9) = 19
Cards(10) = 23
Cards(11) = 95
? What exactly do you want to do? Move each card to a random place?
I have researched the fischer-Yates method. I assume you will be using the computational method? To reduce time taken.

You would need to create 2 variables to hold the temporary values. One for the lastNumber and one for the moveNumber. You would then need to generate a random number in a for loop, between 11 and n (with n getting incrementally smaller after each shuffle.

You would move the array value at cards(n) to moveNumber, and move cards(11) to lastNumber. Then move the cards(n) value to cards(11) and cards(11) value to cards(n) to effectively swap the values. Smile
Why not just generate a random number between 0 and 1 and times it by 100? Then you can have properly random values or all he cards Smile If you round it, you'll be fne.

Also, I'd implement it in a loop:

For count As Integer = 0 to 10

Cards(count) = rndNumber

Next
Zash, do you want to rearrange your numbers? Or generate new ones each time?
I want to rearrange the numbers. Technically, I don't care if new ones are generated as long as there are 6 pairs.
Well my method in my OP would work fine for you Smile
Thank you Tom. I figured it out, here's the code if you're interested:

' Declare Card Values
Cards(0) = 60
Cards(1) = 37
Cards(2) = 84
Cards(3) = 23
Cards(4) = 19
Cards(5) = 95
Cards(6) = 37
Cards(7) = 60
Cards(8) = 84
Cards(9) = 19
Cards(10) = 23
Cards(11) = 95 

' Swap Values (J, I, and temp are declared integers)
For I = 11 to 0 Step -1
J = Rnd * 11
temp = Cards(J)
Cards(J) = Cards(I)
Cards(I) = temp
Next I