From a8f816f984ad98f59942aae06eff775816bf83f8 Mon Sep 17 00:00:00 2001 From: Jessica Kwok Date: Wed, 24 Mar 2021 08:12:31 -0700 Subject: [PATCH] Add solution using Ruby methods --- data_structures/arrays/shuffle_array.rb | 28 +++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/data_structures/arrays/shuffle_array.rb b/data_structures/arrays/shuffle_array.rb index b4c6431..2f1b13f 100644 --- a/data_structures/arrays/shuffle_array.rb +++ b/data_structures/arrays/shuffle_array.rb @@ -34,6 +34,34 @@ def shuffle(nums, n) result end +# nums = [2, 5, 1, 3, 4, 7] +# n = 3 +# print(shuffle(nums, n)) +# # Output: [2,3,5,4,1,7] +# nums = [1, 2, 3, 4, 4, 3, 2, 1] +# n = 4 +# print(shuffle(nums, n)) +# # Output: [1,4,2,3,3,2,4,1] +# nums = [1, 1, 2, 2] +# n = 2 +# print(shuffle(nums, n)) +# # Output: [1,2,1,2] + +# +# Approach 2: Use Ruby methods .insert() and .delete_at() +# +# Time Complexity: O(N) +# + +def shuffle(nums, n) + current_index = 1 + (0..n-1).each do |i| + nums.insert(current_index, nums.delete_at(i + n)) + current_index += 2 + end + nums +end + nums = [2, 5, 1, 3, 4, 7] n = 3 print(shuffle(nums, n))