using C++ This is the first part of a project to deal 13 cards to 4 players from
ID: 3813962 • Letter: U
Question
using C++
This is the first part of a project to deal 13 cards to 4 players from a shuffled deck of 52 cards. Each card in the deck will be represented by an integer from 0 to 51. We will see later how to translate the integer into a string representing a card.
The deck and each hand will be represented by a vector of ints. The vectors should be declared in the main function and not declared globally.
void unwrap(deck) # load the deck vector with integers in order from 0 to 51
void shuffle(deck) # shuffle the deck vector using random_shuffle method - see pages 1008 and 1014 in the text
You can use the debugger to show these functions are working correctly.
Explanation / Answer
#include <iostream>
#include <vector>
#include <ctime>
bool find(const std::vector<int>& vec, int index)
{
for (int i = 0; i < vec.size(); ++i){
if ( index == vec[i] )
return true;
}
return false;
}
void shuffle(int array[], const int size)
{
int temp[size];
std::vector<int> indices;
for ( int i(0); i < size; ++i)
temp[i] = array[i];
int index = rand() % size;
indices.push_back(index);
for ( int i = 0; i < size; ++i){
if ( i == 0 )
array[i] = temp[index];
else{
while( find(indices, index) )
index = rand()%size;
indices.push_back(index);
array[i] = temp[index];
}
}
}
int main(void)
{
srand((unsigned int)time(NULL));
int a[7] = {1,2,3,4,5,6,7};
for ( int i = 0; i < 7; ++i)
std::cout << a[i] << " ";
std::cout << std::endl;
shuffle(a, 7);
for ( int i = 0; i < 7; ++i)
std::cout << a[i] << " ";
std::cout << std::endl;
return 0;
}
The result:
1 2 3 4 5 6 7
3 7 1 6 4 5 2
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.