vendredi 29 novembre 2019

C++ Fisher-Yates shuffle not working properly

I am attempting to implement the Fisher-Yates shuffle for a C++ Poker project.

I found this Code Review link that I used to implement my project.

My current code is below:

#include <iostream>
using namespace std;
#include "Card.h"
#include "Deck.h"

// Inspired by: https://codereview.stackexchange.com/questions/39001/fisher-yates-modern-shuffle-algorithm
void shuffleDeck(vector<Card> cards){
    random_device random;
    mt19937 mersenne_twister(random());
    uniform_int_distribution<uint8_t> distribution;
    for (auto i = cards.size() - 1; i > 0; i--){
        distribution.param(uniform_int_distribution<uint8_t>::param_type(0, i));
        swap(cards[i], cards[distribution(mersenne_twister)]);
    }

} //end shuffleDeck

int main(){
    Deck myDeck;
    vector<Card> theDeck = myDeck.getDeck();

    cout << "PRE SHUFFLE " << endl;

    for (unsigned int i = 0; i < theDeck.size(); i++){
        cout << theDeck[i].getRank() << theDeck[i].getSuit() << endl;
    }

    shuffleDeck(theDeck);

    cout << " POST SHUFFLE " << endl;

    for (unsigned int i = 0; i < theDeck.size(); i++){
        cout << theDeck[i].getRank() << theDeck[i].getSuit() << endl;
    }

}

I get the following for results:

PRE SHUFFLE
2C
3C
4C
5C
6C
7C
8C
9C
10C
2D
3D
4D
5D
6D
7D
8D
9D
10D
2H
3H
4H
5H
6H
7H
8H
9H
10H
2S
3S
4S
5S
6S
7S
8S
9S
10S
JC
KC
QC
AC
JH
KH
QH
AH
JS
KS
QS
AS
JD
KD
QD
AD
 POST SHUFFLE
2C
3C
4C
5C
6C
7C
8C
9C
10C
2D
3D
4D
5D
6D
7D
8D
9D
10D
2H
3H
4H
5H
6H
7H
8H
9H
10H
2S
3S
4S
5S
6S
7S
8S
9S
10S
JC
KC
QC
AC
JH
KH
QH
AH
JS
KS
QS
AS
JD
KD
QD
AD

I should note that the code compiles fine and there are no errors.

I would expect the POST SHUFFLE results to be different. I don't know what exactly, since it is a randomized shuffle, so I cannot post exact "expected results". But the shuffle isn't happening at all. What am I doing wrong that theDeck object is not shuffling?

Aucun commentaire:

Enregistrer un commentaire