Can I shuffle values inside an array?

cards [55]= {1,2,2,3,3,3,4,4,4,4,5,5,5,5,5,6,6,6,6,6,6,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10};

How do I shuffle the values?
Last edited on
Thank you
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <algorithm>
#include <random>

using namespace std;

const int DeckSize = 55;

void init(int *cards) {
    for (int n = 1, i = 0; n <= 10; ++n)
        for (int j = 0; j < n; ++j)
            cards[i++] = n;
}

void shuffle(int *cards) {
    static default_random_engine rnd(random_device{}());
    shuffle(cards, cards + DeckSize, rnd);
}

void print(const int *cards) {
    for (int i = 0; i < DeckSize; ++i)
        cout << cards[i] << ' ';
    cout << '\n';
}

int main()
{
    int cards[DeckSize];
    init(cards);
    print(cards);
    shuffle(cards);
    print(cards);    
}

Last edited on
Bro, why do we use constant integers? or const chars? Sorry for asking this, I'm just learning C++ on my own.
const is for when you don't want something to be changed.
The deck size is fixed, so make it const.

const is sometimes required, for example in an array bound, which is another reason to make the deck size const.

 
int deck[DeckSize];  // DeckSize must be const (in standard C++) 

An important use of const is to make something non-modifiable through a pointer or reference.

const char* is technically required when pointing to a string literal, since the characters in a string literal are not-writeable.

1
2
const char* str = "hello world";
// str[2] = 'x';  // illegal statement; probably segfault if run 

The most important use is in function parameters:

1
2
3
4
// This function promises not to modify the ints that deck points to.
void print(const int* deck) {
    // ...
}
Topic archived. No new replies allowed.