[ create a new paste ] login | about

Link: http://codepad.org/sZgEiMsq    [ raw code | output | fork ]

C++, pasted on Feb 1:
// 
// Shuffling Exercise Shell
// 

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

// *********** class definition
class DeckOfCards{
public:
	DeckOfCards();  //constructor
	void shuffle();
	void deal();
private:
	int deck[4][13];   // two dimensional array (4 rows x 13 columns)
};


int main(){

	DeckOfCards myDeck1;

	myDeck1.deal();

	cout << "************************* now shuffle *******" << endl;

	myDeck1.shuffle();
	myDeck1.deal();
	

	return (0);

}


// ********************* class methods (functions) ****************

//constructor
DeckOfCards::DeckOfCards(){

	int card = 1;

	// populate the private deck array with 52 cards
	for(int row=0; row<=3; row++){
		for(int column=0; column <=12; column++){
			deck[row][column]=card;
			card++;
		}
	}

	srand( time(0) );  //seed random number generator
}

void DeckOfCards::shuffle(){

	// Exercise:  randomize the deck here
	
    int row; // represents suit value of card
     int column; // represents face value of card

    // for each of the 52 cards, choose a slot of the deck randomly
     for ( int card = 1; card <= 52; card++ )
     {
        do // choose a new random location until unoccupied slot is found
        {
           row = rand() % 4; // randomly select the row
           column = rand() % 13; // randomly select the column
        } while( deck[ row ][ column ] != 0 ); // end do...while

        // place card number in chosen slot of deck
        deck[ row ][ column ] = card;
     } // end for
  } // end function shuffle


void DeckOfCards::deal(){
	
	// output all 52 cards
	for(int row=0; row<=3; row++){
		for(int column=0; column <=12; column++){
			cout << deck[row][column] << "  " ;   // each element initially is assigned  0;
		}
	cout << endl;
	}

}


Output:
1
2
3
4
5
6
7
1  2  3  4  5  6  7  8  9  10  11  12  13  
14  15  16  17  18  19  20  21  22  23  24  25  26  
27  28  29  30  31  32  33  34  35  36  37  38  39  
40  41  42  43  44  45  46  47  48  49  50  51  52  
************************* now shuffle *******

Timeout


Create a new paste based on this one


Comments: