Geister Posted January 1, 2019 Share Posted January 1, 2019 (edited) I'm trying to create a Basic XL shuffle routine using the Fisher-Yates algorithm found here. For some reason I can't seem to understand, the result of the shuffle always puts the last card (51) in the first position. All the other cards seem to shuffle randomly. Maybe I have just been looking at this too long and am missing something obvious. I'd appreciate anyone looking at this and pointing out my mistake. I'm using the BXL Random function which returns a number between the first and second parameter (inclusive) as it closely approximates the C rand() function which returns a number between 0 and 32767 (inclusive). BXL throws an out of bounds error if I use 0 and 32767, but works OK if I use 0..32766 or 1..32767. The value of K does not appear to be the same each time the code is run and yet the value in the first position of of the Deck array is always 51 after the shuffle. Here is the Basic XL code: 100 Dim Deck(52),Cards(5,5) 105 Rem INITIALIZE THE ARRAY 110 For X=0 To 51:Deck(X)=X:Next X 115 Rem SHUFFLE THE ARRAY 120 For I=0 To 51 130 J=(52-I):K=Random(1,32767) 135 Rem R IS K MOD J 140 R=K-(Int(K/J)*J) 145 Rem SWAP CARDS 150 L=Deck(I):Deck(I)=Deck(R):Deck(R )=L 155 Print R, 160 Next I 165 Print :Print 170 For I=0 To 51 180 Print Deck(I);" "; 190 Next I The code above is being run in Altirra 2.90 using the BXL cart and extensions disk loaded up on an NTSC XE with 320K Rambo enabled for no particular reason. Ignore the Cards Matrix as that is unused (meant to be the 5 X 5 grid of cards arranged on screen in my Monaco Solitare game). Thanks for any comments. Edited January 1, 2019 by Geister Quote Link to comment Share on other sites More sharing options...
phaeron Posted January 1, 2019 Share Posted January 1, 2019 Needs R=R+I so that the randomly picked shuffle position is from the end instead of the start. 1 Quote Link to comment Share on other sites More sharing options...
Geister Posted January 1, 2019 Author Share Posted January 1, 2019 Thank you. That is it! Now that I look at the original C code I can see that. I was too focused on getting the MOD (%) function to work properly. v int r = i + (rand() % (52 -i)); ^ It works perfectly now. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.