Add solution using Ruby methods

This commit is contained in:
Jessica Kwok 2021-03-24 08:12:31 -07:00
parent 16fd8c756f
commit a8f816f984

View file

@ -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))