Shuffle a Deck Cards

Given a function that generates perfectly random numbers between 1 and k (inclusive), where k is an input, write a function that shuffles a deck of cards represented as an array using only swaps.

Example:

Output:

42 8 30 38 45 47 32 15 3 22 12 37 50 4 48 39 2 23 7
26 31 41 18 14 44 40 36 49 51 16 9 1 24 20 43 33 28
29 19 0 13 11 10 46 35 5 21 25 27 34 6 17

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

int getRandomNumber(int k)
{
    return rand() % k + 1;
}

vector<intshuffleCardDeck()
{
    vector<intcards;
    for (int x = 0x < 52x++)
    {
        cards.push_back(x);
    }

    for (int i : cards)
    {

        int newPos = i + getRandomNumber(52 - i - 1);
        int temp = cards[newPos];
        cards[newPos] = cards[i];
        cards[i] = temp;
    }
    return cards;
}
int main()
{

    vector<intcards = shuffleCardDeck();
    for (int j = 0j < cards.size(); j++)
    {
        cout << cards[j] << " ";
    }
}


No comments:

Post a Comment