Pack of cards?

vapourmile · 6986

Offline vapourmile

  • ZX80
  • *
    • Posts: 17
on: June 30, 2015, 09:07:35 am
I think I've asked this before, but I'll throw it out again and see what happens....

Ok, imagine you're writing a program to shuffle a pack of cards.

Let's say the cards are simply numbered 1-52 and you have a program further down the line to convert an integer X to a face value and suit given X:52>=X>=1.

You have a standard random number generator, let's say

Rand(X)

Which will return a random integer between 0 and X

You can have as many arrays as you want, say:

Array deck = int[52]

Which will produce an array "deck" with elements from 0-51.


You can index into the array with .variable e.g:

int deal = deck.cardnumber


Makes sense?

Ok, now write a piece of pseudo code describing an algorithm which will deal a shuffled deck of cards.


I noticed you wrote a card game, so you'll be good at this! It took me quite a long time to think of something you'd be good at. :-)

Ok, off you go then.... anybody that is. Programmers, non programmers.....


The question is: How do you write a program which deals a shuffled deck of cards?
« Last Edit: June 30, 2015, 09:09:31 am by vapourmile »



Offline sverx

  • RBP Member
  • IBM PC
  • *****
    • Posts: 516
  • "Ow!!! What's that ?!?!"
    • My NDS folder
Reply #1 on: June 30, 2015, 01:15:10 pm
I would swap two random elements of the card array say 100.000 times



Offline headkaze

  • Administrator
  • Blue Gene Super Computer
  • **********
    • Posts: 7838
Reply #2 on: June 30, 2015, 07:20:31 pm
This is how we do it in WinSol

Code: [Select]
// This will shuffle the deck into a random order
for (int i=0; i<(m_deck.size()-1); i++)
{
// Get a random position for this card
int r = i + (rand() % (m_deck.size()-i));

swap(m_deck[i], m_deck[r]);
}



Offline Sokurah

  • RBP Member
  • Cray-1 Super Computer
  • *****
    • Posts: 724
    • Tardis Remakes
Reply #3 on: June 30, 2015, 11:01:42 pm
I would do it like this;

1. Get random nunber between 2 and 52.
2. Move that card in the deck to the top of the deck.
3. Repeat lots of times.

Done. :)