Home > OS >  How to move an element of an array to the beginning of the array
How to move an element of an array to the beginning of the array

Time:01-13

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?

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)
  # 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

CodePudding user response:

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..]]
  • Related