Homework 31
Complete the following program (or write your own from scratch if you prefer) that reads in 5 cards (as in a hand of playing cards) and writes them out sorted by suit (first clubs, then diamonds, then hearts, then spades) and, within a group of cards of the same suit, by face value (ace high). A typical run of your program might look like this:
Enter cards: 9C QD AC 7C 10DCards sorted: 7C 9C AC 10D QD
You’ll need to
1. create
a struct to represent a Card as having
fields for a char giving the
suit (C, D, H,
S) and an int
giving the face value (where 11 means jack, 12 means queen, 13 means king, and
14 means ace),
2. provide the print function which prints out the sorted cards, and
3. provide the before function which is used by the selectionSort function.
Turn in: A paper copy of your source code and a screen capture of your program running on the above input.
// DMN
// Hmwk 31
// This program reads in 5 cards (9C, QD, etc) and writes them
out sorted by suits
// (clubs,
diamonds, hearts, spades, and then within a group of cards of the
// same suit
by face value (lowest to highest, with ace being high).
#include <iostream>
using namespace std;
// prototypes
void selectionSort(Card*, int);
void fetchCards(Card*,int);
int main(){
Card* deck = new Card[5];
fetchCards(deck, 5);
selectionSort(deck,5);
print(deck,5);
delete [] deck; // deallocate
dynamic memory
deck = NULL; // defensive programming
return 0;
}
void fetchCards(Card* deck,int N){
char temp;
cout << "Enter
Cards: ";
for(int i=0;i<N;i++){
cin >> temp;
// Deal with the 10, have to read
another char
if (temp == '1')
cin >> temp;
cin >> deck[i].suit;
// Just in case the user entered the
suit in lower case.
deck[i].suit = toupper(deck[i].suit);
switch (temp){
case
'J':
case
'j': deck[i].face=11; // jack
break;
case
'Q':
case
'q': deck[i].face=12; // queen
break;
case
'K':
case
'k': deck[i].face=13; // king
break;
case
'A':
case
'a': deck[i].face=14; // ace
break;
case '0': deck[i].face=10; // The face was a 10
break;
default: deck[i].face = temp - '0';
}
}
}
void selectionSort(Card *arrayIn, int N){
for(int length = N; length > 1; length--){
// Find imax, the index of the largest
int
imax = 0, i;
for(i = 1; i < length; i++)
if (before(arrayIn[imax],arrayIn[i]))
imax = i;
// Swap arrayIn[imax]
& the last element
Card temp = arrayIn[imax];
arrayIn[imax] = arrayIn[length - 1];
arrayIn[length - 1] = temp;
}
}
syntax highlighted by Code2HTML, v. 0.9.1