Last active
December 25, 2022 18:29
-
-
Save dharshan/ea817cd759cd5868bd2d1788fae29368 to your computer and use it in GitHub Desktop.
Ruby cyclic rotation of array elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CyclicRotation | |
def solution(array, num) | |
new_array = Array.new(array.length) | |
array.each_with_index do |element, idx| | |
# (index + element) % array_size will give new index value to which we have to insert current value | |
new_array[(idx + num) % array.length] = element | |
end | |
new_array | |
end | |
end | |
puts CyclicRotation.new.solution([3, 8, 9, 7, 6], 3).join(',') | |
puts CyclicRotation.new.solution([1, 2, 3, 4], 1).join(',') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment