• July 19, 2018, 10:10:30 AM
  • Welcome, Guest
Advanced search  

News:

Author Topic: Pack of cards?  (Read 2143 times)

vapourmile

  • ZX80
  • *
  • Offline Offline
  • Posts: 17
Pack of cards?
« on: June 30, 2015, 08: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, 08:09:31 AM by vapourmile »
Logged

sverx

  • RBP Member
  • IBM PC
  • *****
  • Offline Offline
  • Posts: 495
  • "Ow!!! What's that ?!?!"
    • My NDS folder
Re: Pack of cards?
« Reply #1 on: June 30, 2015, 12:15:10 PM »

I would swap two random elements of the card array say 100.000 times
Logged

headkaze

  • Administrator
  • Blue Gene Super Computer
  • **********
  • Offline Offline
  • Posts: 7823
Re: Pack of cards?
« Reply #2 on: June 30, 2015, 06: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]);
}
Logged

Sokurah

  • RBP Member
  • Cray-1 Super Computer
  • *****
  • Offline Offline
  • Posts: 709
    • Tardis Remakes
Re: Pack of cards?
« Reply #3 on: June 30, 2015, 10: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. :)
Logged