-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathShuffleInteger.rb
37 lines (33 loc) · 1.21 KB
/
ShuffleInteger.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Shuffle integers
# Given an array arr[] of n elements in the following format {a1, a2, a3, a4, .., an/2, b1, b2, b3, b4, ., bn/2}, the task is shuffle the array to {a1, b1, a2, b2, a3, b3, , an/2, bn/2} without using extra space.
# Example 1:
# Input: n = 4, arr[] = {1, 2, 9, 15}
# Output: 1 9 2 15
# Explanation: a1=1 , a2=2 , b1=9 , b2=15
# So the final array will be :
# a1, b1, a2, b2 = { 1, 9, 2, 15 }
# Example 2:
# Input: n = 6
# arr[] = {1, 2, 3, 4, 5, 6}
# Output: 1 4 2 5 3 6
# Your Task:
# This is a function problem.
# You don't need to take any input, as it is already accomplished by the driver code.
# You just need to complete the function shuffleArray() that takes array arr[], and an integer n as parameters and modifies the given array according to the above-given pattern.
#
# Expected Time Complexity: O(n).
# Expected Auxiliary Space: O(1).
#---------------
# Naive solution
def shuffleIntegers(arr, n)
dc = nil
ac = []
#-------------------------------------------------------------
# Divide it by 2 - ruby by default it will consider as integer
dc = (n/2)
dc.times { |index| ac << arr[index] << arr[-dc + index] }
return ac
end
arr = [1, 2, 3, 4, 5, 6]
n = 6
p shuffleIntegers(arr, n)