I want to move the element at index 2 to the start of the array [1, 2, 3, 4], the resulting array should look like [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?
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 your 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]
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)
# ruby >= 2.6 arr.dup.then {|a| a.unshift(a.delete_at(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
arr[0..idx] subarray (to the left). This is what the OP meant by "partial rotation" as you're not rotating the entire array.[3,1,2,4], [2,3,1,4], etc. then terminologically speaking I am not sure I could come up with a better explanation of this pattern than partial rotation.def move_element_to_front(arr, idx)
[arr[idx]].concat(arr[0,idx], arr[idx+1..])
end
arr = [:dog, :cat, :pig, :hen]
move_element_to_front(arr, 2)
#=> [:pig, :dog, :cat, :hen]
move_element_to_front(arr, 0)
#=> [:dog, :cat, :pig, :hen]
move_element_to_front(arr, 3)
#=> [:hen, :dog, :cat, :pig]
The operative line of the method could alternatively be expressed
[arr[idx], *arr[0,idx], *arr[idx+1..]]
[1, 2, 3, 4].values_at(2, 0..1, 3)would work (and could be further generalized)i = 2; [1, 2, 3, 4].values_at(i, 0...i, i+1..) #=> [3, 1, 2, 4]. This works for alli,0 <= i <= 3.