From 4689e4e80b479be25f7557d05818f5caa723aafa Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Wed, 5 Feb 2025 18:36:31 -0800 Subject: Initial commit. --- .../easy/design/01_shuffle_an_array.cc | 41 ++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 top-interview-questions/easy/design/01_shuffle_an_array.cc (limited to 'top-interview-questions/easy/design/01_shuffle_an_array.cc') 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 @@ +class Solution { +public: + Solution(vector& nums) + : m_original(nums) {} + + vector reset() { + return m_original; + } + + vector shuffle() { + std::vector 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 m_original; + std::uint64_t m_random = 16240738485554559101; +}; + +/** + * Your Solution object will be instantiated and called as such: + * Solution* obj = new Solution(nums); + * vector param_1 = obj->reset(); + * vector param_2 = obj->shuffle(); + */ -- cgit v1.2.3