UnderwareDESIGN

PlayBASIC => Beginners => Topic started by: ScottB on January 14, 2025, 01:57:24 PM

Title: Simple Question
Post by: ScottB on January 14, 2025, 01:57:24 PM
I've done this alot but I'm slipping lately.

How do I randomize array with no doubles?

Thanks

Scott B


Dim Deck(52)

For J = 0 To 51
   For I = 0 To 51
      
Sub_1:

      Random_Card = Rnd(51) + 1
      
      If Random_Card = Deck(I)
         
         Goto Sub_1
         
      Else
      
         Deck(J) = Random_Card
      
      EndIf
   
   Next I
Next J         
      
      
For I = 0 To 51
   
   Print Deck(I)
   
Next I

Sync

Waitkey

End
Title: Re: Simple Question
Post by: stevmjon on January 14, 2025, 05:49:06 PM
Dim Deck(52)

For J = 0 To 51

Sub_1:

   Random_Card = Rnd(51) + 1  ;  place this outside inner loop to ensure it updates if it loops again
   
   For I = 0 To 51
     
;;Sub_1:

      ;;Random_Card = Rnd(51) + 1
     
      If Random_Card = Deck(I)
         
         Goto Sub_1  ;  start inner loop again if found repeat number
         
      ;;Else
     
         ;;Deck(J) = Random_Card
     
      EndIf
      
   Next I
   
   Deck(J) = Random_Card  ;  update this outside inner loop AFTER all positions checked
   
Next J         


For I = 0 To 51
   
   Print Deck(I)
   
Next I

Sync

Waitkey

End
Title: Re: Simple Question
Post by: kevin on January 14, 2025, 08:39:51 PM
 
 1)  Fill the array with all the possible options
 2)  then sweep through and randomly swap elements, 
 3)  repeat step 2 as needed

 
 see Shuffle Deck of Cards (https://www.underwaredesign.com/forums/index.php?topic=3485.0)