mirror of
https://github.com/TheAlgorithms/Ruby
synced 2025-01-27 19:58:06 +01:00
Add solution using Ruby methods
This commit is contained in:
parent
16fd8c756f
commit
a8f816f984
1 changed files with 28 additions and 0 deletions
|
@ -34,6 +34,34 @@ def shuffle(nums, n)
|
||||||
result
|
result
|
||||||
end
|
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]
|
nums = [2, 5, 1, 3, 4, 7]
|
||||||
n = 3
|
n = 3
|
||||||
print(shuffle(nums, n))
|
print(shuffle(nums, n))
|
||||||
|
|
Loading…
Add table
Reference in a new issue