-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.rb
More file actions
61 lines (42 loc) · 1 KB
/
Solution.rb
File metadata and controls
61 lines (42 loc) · 1 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# @param {Integer[]} nums
# @param {Integer} k
# @return {Void} Do not return anything, modify nums in-place instead.
def rotate(nums, k)
if nums.nil? or nums.size == 1 or k % nums.size == 0
return
end
array_length = nums.size
source_index = 0
current_buffer_value = nums[source_index]
distance = 0
1.upto array_length do
target_index = (source_index + k) % array_length
temp = nums[target_index]
nums[target_index] = current_buffer_value
source_index = target_index
current_buffer_value = temp
distance = (distance + k) % array_length
if distance == 0
source_index = (source_index + 1) % array_length
current_buffer_value = nums[source_index]
end
end
end
# source = [1, 2, 3, 4, 5, 6, 7]
#
# rotate source, 3
#
# print source
#
# puts
#
# source = [1,2,3,4,5,6]
#
# rotate source, 2
#
# print source # Expected: [5,6,1,2,3,4]
#
# puts
source = [1,2,3,4,5,6]
rotate source, 3
print source # Expected: [4,5,6,1,2,3]