1

I'm trying to make it so that if my randomly generated card is the same as any of the currently stored cards it will go back and generate a new random card and store it. I'm having issues with trying to find a way to make it recheck each time a new card has been generated.

I have this at the moment but i need someone else to look at it and tell me how i can change the code to make it work properly.

  For x As Integer = 0 To 21
        drawCard(x)
        While (redraw > 1)
            For y As Integer = 0 To 21
                If randomCards(x) = randomCards(y) Then
                    drawCard(x)
                    redraw += 1
                End If
            Next
        End While
    Next
  • 1
    Are you specifically looking to do it this way or are you just looking to get 22 random cards from a deck (what does your `drawCard` procedure do, actually?)? Also, if you specifically want to do it this way, then what datatype is `randomCards(i)` and how does it check for equality? – John Bustos Mar 28 '14 at 16:32
  • 1
    sounds like what you want is to start the "deck" out in random order and not generate duplicates. if so, you need to shuffle it: http://stackoverflow.com/a/110570/1070452 google will give you some VB solutions if you cant read C# – Ňɏssa Pøngjǣrdenlarp Mar 28 '14 at 16:40

1 Answers1

2

Assuming all you really are looking to do is get 22 random cards out of a deck of 52, the easiest way to do it is to take the numbers 1-52, mix them up and take the first 22 values.

Once you have that, all you need to do is take the cards at those 22 indexes out of your deck and you have a shuffled hand.

To get you started (assuming you're happy with this as a way to do it rather than your previous way), this code will give you the 22 indexes to take from your deck:

Dim rnd As New Random
Dim ShuffledCards As List(Of Integer) = Enumerable.Range(1, 52).OrderBy(Function(i) rnd.Next).Take(22).ToList

In effect, what the second line of code is doing is:

  1. Creating a list of numbers from 1 to 52 Enumerable.Range(1, 52)
  2. Using the a new random number, rnd.Next to select how to order each of these (so the numbers 1-52 get scrambled up)
  3. Takes the first 22 of these Take(22)
  4. Saves it as a list of integers

You may want to look at something like 101 Linq samples or read up on Linq to learn more about Linq as a whole.

Again, I'm not sure if you're ok with this way, but hope it helps!!

PS - Using the same procedure, you can also just directly randomize your deck of cards using the .OrderBy(Function(i) rnd.Next) and skip getting the indexes... Some people prefer the intermediate step, though...

John Bustos
  • 19,036
  • 17
  • 89
  • 151