Jump to content

Problems in understanding code to randomly shuffle an array.

- - - - -

  • Please log in to reply
1 reply to this topic

#1
KL4OR

KL4OR

    Newbie

  • Members
  • Pip
  • 2 posts
Hello,

I have been looking at this code to randomly shuffle an array. I have been trying to adapt it so that when you run it, you don't need to enter any numbers and that it just shuffles itself, but I cannot seem to get it working.

Here is the original code:

// random/deal.cpp - Randomly shuffle deck of cards.

// Illustrates : Shuffle algorithm, srand, rand.

// Improvements: Use classes for Card and Deck.

// Author      : Fred Swartz 2003-08-24


#include <iostream>

#include <cstdlib>   // for srand and rand

#include <ctime>     // for time

using namespace std;


int main() {

    int card[52];    // array of cards;

    int n;           // number of cards to deal

    srand(time(0));  // initialize seed "randomly"

     

    for (int i=0; i<52; i++) {

        card[i] = i;  // fill the array in order

    }

    

    while (cin >> n) {    

        //--- Shuffle elements by randomly exchanging each with one other.

        for (int i=0; i<52; i++) {

            int r = rand() % 52;  // generate a random position

            int temp = card[i]; card[i] = card[r]; card[r] = temp;

        }

        

        //--- Print first n cards as ints.

        for (int c=0; c<n; c++) {

            cout << card[c] << " ";  // Just print number

        }

        cout << endl;

    }

   

   return 0;

}

I think it has something to do with
  while (cin >> n) {  
, but I'm not exactly what it's doing. I would really appreciate it if anyone could offer their advice!

#2
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1
The while loop will run as long as you enter a valid integer, and will determine how many cards do you want to print (2nd for loop).

If you want it to run indefenetly, simply make while loop condition to true, or add another counter for fixed (or ask user to input) number of iterations.
A conclusion is where you got tired of thinking.
#define class struct    // All is public.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users