Created
June 16, 2021 21:19
-
-
Save alexismansilla/a95bc1c87b71192de33fc35c6a9e57e4 to your computer and use it in GitHub Desktop.
Create a small script that rotates elements without using rotate method (ruby)
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
require 'rspec' | |
# Returns a new array with the rotated positions | |
# when the count is major to one I'm going to call the divmod method | |
# | |
# Finally the result has summed the elements with different positions based on divmod method. | |
# | |
# | |
# @param ary [Array<Integer>] | |
# @param count [Integer] | |
# | |
# @return [Array<Integer>, String] the new array or message | |
# | |
def array_rotation(ary, count = 1) | |
return 'It is an empty array' unless ary.length > 0 | |
divmod = count.divmod(ary.length)[1] | |
ary.last(ary.length - divmod) + ary.first(divmod) | |
end | |
describe '#array_rotation' do | |
context 'when an array is empty' do | |
it 'returns a message' do | |
expect(array_rotation([], 2)).to eq('It is an empty array') | |
end | |
end | |
context 'when an array is not empty' do | |
it 'when the rotation size is empty but default it must rotate once' do | |
expect(array_rotation([1,2,3,4])).to eq([2,3,4,1]) | |
end | |
it 'when the rotation size is negative' do | |
expect(array_rotation([1,2,3,4], -2)).to eq([3,4,1,2]) | |
end | |
it 'when the rotation size is 2' do | |
expect(array_rotation([1,2,3,4], 2)).to eq([3,4,1,2]) | |
end | |
it 'when the rotation size is 10' do | |
expect(array_rotation([1,2,3,4], 10)).to eq([3,4,1,2]) | |
end | |
it 'when the rotation size is impar' do | |
expect(array_rotation([1,2,3,4], 5)).to eq([2,3,4,1]) | |
end | |
it 'when the rotation size is a big number' do | |
expect(array_rotation([1,2,3,4], 500000000000000001)).to eq([2,3,4,1]) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment