Bridge hands problem in C++
- #include <iostream>
- #include <array>
- #include <vector>
- //#include <cstdio>
- //#include <cmath>
- #include <cstdlib>
- #include <ctime>
- //#include <iterator>
- //os x: clang++ -std=c++11 -stdlib=libc++ -g -Wall bridgehands.cpp -o bridgehands
- //linux: clang++ -std=c++11 -g -Wall bridgehands.cpp -o bridgehands.linux
- std::array<int,52> shuffle_deck ()
- {
- std::vector<int> unshuffled_deck (52,0);
- //initialize unshuffled deck
- for (int i = 0; i < 52; i++) unshuffled_deck[i] = i;
- srand (time (NULL));
- std::array<int,52> shuffled_deck;
- shuffled_deck.fill(-1);
- /* shuffle the deck by taking a random
- card from the unshuffled deck then
- deleting the card */
- for (int i = 0; i < 52; i++) {
- int random_card = rand() % (52 - i);
- shuffled_deck[i] = unshuffled_deck[random_card];
- unshuffled_deck.erase(unshuffled_deck.begin() + random_card);
- }
- return shuffled_deck;
- }
- template<typename C>
- void print_sequence(C& items) {
- for (auto const& item : items) std::cout << item << ' ';
- }
- std::string convert_card (int card)
- {
- std::array<std::string,13> card_strings =
- {{ "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"}};
- return card_strings[card % 13];
- }
- template<typename C>
- void print_card_sequence(const C& cards) {
- for (auto const& card : cards) std::cout << convert_card(card) << ' ';
- }
- std::array<std::array<int, 13>, 4> deal_cards (std::array<int,52> shuffled_cards)
- {
- std::array<std::array<int,13>, 4> dealt_cards;
- for (int i = 0; i < 52; i++)
- {
- dealt_cards[i%4][i%13] = shuffled_cards[i];
- }
- return dealt_cards;
- }
- struct Hand
- {
- //store cards as an array of four vectors
- std::array<std::vector<int>,4> cards;
- void add_cards(std::array<int,13> new_cards)
- {
- std::sort(new_cards.begin(), new_cards.end());
- std::reverse(new_cards.begin(),new_cards.end());
- for (auto card : new_cards) {
- cards[(card / 13)].push_back(card);
- }
- }
- std::array<std::string,4> suit_labels {{"C", "D", "H", "S"}};
- void print_hand(void)
- {
- for (int i = 3; i > -1; i--)
- {
- std::cout << suit_labels[i] << ": ";
- print_card_sequence(cards[i]);
- std::cout << "\n";
- }
- }
- };
- void print_all_hands (std::array<std::array<int,13>, 4> dealt_cards)
- {
- std::array<std::string,4> hand_labels = {{"NORTH", "EAST", "SOUTH", "WEST"}};
- for (int i = 0; i < 4; i ++)
- {
- std::cout << hand_labels[i] << "\n";
- Hand this_hand;
- this_hand.add_cards(dealt_cards[i]);
- this_hand.print_hand();
- std::cout << "\n";
- }
- }
- int main(int argc, char* argv[])
- {
- std::array<int,52> shuffled_deck = shuffle_deck();
- std::array<std::array<int,13>, 4> dealt_cards = deal_cards(shuffled_deck);
- //print_sequence(dealt_cards[0]);
- //Hand north;
- //north.add_cards(dealt_cards[0]);
- //north.print_hand();
- print_all_hands(dealt_cards);
- return 0;
- }
No comments:
Post a Comment