diff options
Diffstat (limited to 'top-interview-questions/easy/design/01_shuffle_an_array.cc')
| -rw-r--r-- | top-interview-questions/easy/design/01_shuffle_an_array.cc | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/top-interview-questions/easy/design/01_shuffle_an_array.cc b/top-interview-questions/easy/design/01_shuffle_an_array.cc new file mode 100644 index 0000000..5c40d60 --- /dev/null +++ b/top-interview-questions/easy/design/01_shuffle_an_array.cc | |||
| @@ -0,0 +1,41 @@ | |||
| 1 | class Solution { | ||
| 2 | public: | ||
| 3 | Solution(vector<int>& nums) | ||
| 4 | : m_original(nums) {} | ||
| 5 | |||
| 6 | vector<int> reset() { | ||
| 7 | return m_original; | ||
| 8 | } | ||
| 9 | |||
| 10 | vector<int> shuffle() { | ||
| 11 | std::vector<int> shuffled = m_original; | ||
| 12 | for (size_t i = 0; i < shuffled.size(); ++i) { | ||
| 13 | const size_t j = random() % shuffled.size(); | ||
| 14 | std::swap(shuffled[i], shuffled[j]); | ||
| 15 | } | ||
| 16 | return shuffled; | ||
| 17 | } | ||
| 18 | |||
| 19 | private: | ||
| 20 | size_t random() { | ||
| 21 | uint64_t x = m_random; | ||
| 22 | |||
| 23 | // xorshift64 | ||
| 24 | x ^= x << 13; | ||
| 25 | x ^= x >> 7; | ||
| 26 | x ^= x << 17; | ||
| 27 | |||
| 28 | m_random = x; | ||
| 29 | return x; | ||
| 30 | } | ||
| 31 | |||
| 32 | std::vector<int> m_original; | ||
| 33 | std::uint64_t m_random = 16240738485554559101; | ||
| 34 | }; | ||
| 35 | |||
| 36 | /** | ||
| 37 | * Your Solution object will be instantiated and called as such: | ||
| 38 | * Solution* obj = new Solution(nums); | ||
| 39 | * vector<int> param_1 = obj->reset(); | ||
| 40 | * vector<int> param_2 = obj->shuffle(); | ||
| 41 | */ | ||
