summaryrefslogtreecommitdiff
path: root/top-interview-questions/easy/design/01_shuffle_an_array.cc
blob: 5c40d60234b5cffd67ea1c05245ae67001e9fb1d (plain)
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
35
36
37
38
39
40
41
class Solution {
public:
    Solution(vector<int>& nums)
      : m_original(nums) {}

    vector<int> reset() {
        return m_original;
    }

    vector<int> shuffle() {
        std::vector<int> shuffled = m_original;
        for (size_t i = 0; i < shuffled.size(); ++i) {
            const size_t j = random() % shuffled.size();
            std::swap(shuffled[i], shuffled[j]);
        }
        return shuffled;
    }

private:
    size_t random() {
        uint64_t x = m_random;

        // xorshift64
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;

        m_random = x;
        return x;
    }

    std::vector<int> m_original;
    std::uint64_t    m_random = 16240738485554559101;
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(nums);
 * vector<int> param_1 = obj->reset();
 * vector<int> param_2 = obj->shuffle();
 */