Home > Software engineering >  Is there a built in function that will shuffle and array in c ?
Is there a built in function that will shuffle and array in c ?

Time:11-22

I am trying to create a deck of cards in c , i store that deck in an array array<Card, 52> deckOfCards = generateCards() once I create the array is there any way to shuffle the objects inside of it easily, for example in java you could use the shuffle() algorithm and the objects would be shuffled, any help would be appreciated!

Thank you!

CodePudding user response:

Yes, c does have it's shuffle. However, you must also add a random generator in there manually, which could be daunting at a first glance. However, if you don't really care the exact generator and engine being used, then this could be done simply with:

std::shuffle(deckOfCards.begin(), deckOfCards.end(), std::default_random_engine{/*optional seed*/});

or

std::shuffle(deckOfCards.begin(), deckOfCards.end(), std::random_device{});

Where the first one is deterministic and the second one is non-deterministic.

CodePudding user response:

Put them in a std::vector and use

std::random_shuffle ( myvector.begin(), myvector.end() );

Or, for an array:

random_shuffle(std::begin(a), std::end(a))

  • Related