Skip to content

Instantly share code, notes, and snippets.

@dharshan
Last active December 25, 2022 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dharshan/ea817cd759cd5868bd2d1788fae29368 to your computer and use it in GitHub Desktop.
Save dharshan/ea817cd759cd5868bd2d1788fae29368 to your computer and use it in GitHub Desktop.
Ruby cyclic rotation of array elements
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