I want to partially rotate the array from [1, 2, 3, 4]
to [3, 1, 2, 4]
.
My solution was to do the following
[3] ([1, 2, 3, 4] - [3])
Is there a better way to do this?
CodePudding user response:
A method that takes the first n
elements from an array and rotates them by one, then adds back the remaining elements.
def rotate_first_n_right(arr, n)
arr[0...n].rotate(-1) arr[n..-1]
end
rotate_first_n_right([1,2,3,4], 3)
# => [3, 1, 2, 4]
This does fail if we try to use it on an array that is too short, as the arr[n..-1]
slice will yield nil
which will cause an error when we try to add it to the first array.
We can fix this by expanding both slices into a list.
def rotate_first_n_right(arr, n)
[*arr[0...n].rotate(-1), *arr[n..-1]]
end
To see why this works, a very simple example:
[*[1, 2, 3], *nil]
# => [1, 2, 3]
A problem with you example is what happens if 3
occurs in the array more than once. E.g.
[1,2,3,3,3,4] - [3]
# => [1, 2, 4]
CodePudding user response:
Not sure what you mean about "rotation" as this is not exactly a rotation but you could go with
def move_element_to_front(arr, idx)
arr = arr.dup
arr.unshift(arr.delete_at(idx))`
end
This will move the element at idx
to the first position in the returned Array