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 726 31 41 18 14 44 40 36 49 51 16 9 1 24 20 43 33 2829 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<int> shuffleCardDeck(){vector<int> cards;for (int x = 0; x < 52; x++){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<int> cards = shuffleCardDeck();for (int j = 0; j < cards.size(); j++){cout << cards[j] << " ";}}
No comments:
Post a Comment