Created
July 22, 2011 20:56
-
-
Save TheBuzzSaw/1100411 to your computer and use it in GitHub Desktop.
Card Shuffle Program
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdlib> | |
#include <cstring> | |
#include <ctime> | |
#include <iostream> | |
#include <fstream> | |
using namespace std; | |
template<typename T> | |
class Deck | |
{ | |
public: | |
Deck(size_t inSize = 64) | |
{ | |
mSize = inSize ? inSize : 64; | |
mCards = new T[mSize]; | |
for (size_t i = 0; i < mSize; ++i) | |
mCards[i] = static_cast<T>(i + 1); | |
} | |
Deck(const Deck& inDeck) | |
{ | |
mSize = inDeck.mSize; | |
mCards = new T[mSize]; | |
memcpy(mCards, inDeck.mCards, mSize * sizeof(T)); | |
} | |
~Deck() | |
{ | |
delete [] mCards; | |
} | |
inline operator T*() { return mCards; } | |
inline operator const T*() const { return mCards; } | |
void shuffle() | |
{ | |
Deck clone(*this); | |
T** pointers = new T*[mSize]; | |
for (size_t i = 0; i < mSize; ++i) | |
pointers[i] = clone.mCards + i; | |
for (size_t i = 0; i < mSize; ++i) | |
{ | |
size_t remaining = mSize - i; | |
size_t pick = rand() % remaining; | |
mCards[i] = *pointers[pick]; | |
if (pick < remaining - 1) | |
pointers[pick] = pointers[remaining - 1]; | |
} | |
delete [] pointers; | |
} | |
friend ostream& operator<<(ostream& inStream, const Deck& inDeck) | |
{ | |
for (size_t i = 0; i < inDeck.mSize; ++i) | |
inStream << ' ' << inDeck.mCards[i]; | |
return inStream; | |
} | |
private: | |
size_t mSize; | |
T* mCards; | |
}; | |
int main(int argc, char** argv) | |
{ | |
srand(time(NULL)); | |
Deck<int> d(16); | |
ofstream fout("shuffle.txt"); | |
cout << d << endl; | |
fout << d << endl; | |
for (size_t i = 0; i < 8; ++i) | |
{ | |
d.shuffle(); | |
cout << d << endl; | |
fout << d << endl; | |
} | |
fout.close(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment