// Store the original deck
Card* temp = deck.Cards;
// For loop that iterates through array
for (int i = 0; i < 52; i ) {
int randomIndex = rand() % 52;
deck.Cards[i] = deck.Cards[randomIndex];
deck.Cards[randomIndex] = temp[i];
}
I want to shuffle an array that I already created of size 52. This is a segment of my code, for some reason the resulting array comes out with many values missing, as some are duplicated. Shouldn't the last two lines just swap the values?
CodePudding user response:
temp
is another pointer to the same array - the cards aren't duplicated, so when you overwrite a card in the original array in the loop body, the same change will also be "visible" via temp
.
The best practice for switching elements in an array is to use a temporary variable for the element being switched. E.g.:
// For loop that iterates through array
for (int i = 0; i < 52; i ) {
int randomIndex = rand() % 52;
Card temp = deck.Cards[i];
deck.Cards[i] = deck.Cards[randomIndex];
deck.Cards[randomIndex] = temp;
}
CodePudding user response:
In C you shouldn't use pointers if you don't have to. And did you know the C standard library comes with a shuffle function? By using that you don't even have to implement a swap function yourself, and you reuse tested code.
You could also have used std::swap(deck.Cards[i], deck.Cards[randomIndex]);
#include <algorithm>
#include <array>
#include <iostream>
#include <random>
class Card
{
public:
Card() :
m_id{ g_id }
{
};
std::size_t id() const
{
return m_id;
}
private:
std::size_t m_id;
static std::size_t g_id;
};
// to generate a new instance id for each Card
std::size_t Card::g_id{ 0 };
// or make a Cards member in Deck that is a std::array
// this is just a short version to show you the direction.
using Deck = std::array<Card, 52>;
int main()
{
// random generator stuff C style
std::random_device rd{};
std::default_random_engine random_generator{ rd() };
// a deck
Deck deck;
// show start order of cards
for (const auto& card : deck) std::cout << card.id() << " ";
std::cout << "\n";
// shuffle the cards
// https://en.cppreference.com/w/cpp/algorithm/shuffle
std::shuffle(deck.begin(), deck.end(), random_generator);
// show shuffled order of the cards
for (const auto& card : deck) std::cout << card.id() << " ";
std::cout << "\n";
return 0;
}