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!


Sign In
Create Account

Back to top









