Home > Software engineering >  Sorting an array according to an element inside this array
Sorting an array according to an element inside this array

Time:03-07

I need to order my array according to an element of it, the reference element can vary. For example, I would like the 3 to become the first element of the array and the 1, 2 to be put at the end.

  • array = [1, 2, 3, 4, 5, 6]
  • new_array = [3, 4, 5, 6, 1, 2]

The element may vary. If I start from 5, the behavior must be the same: the elements that precede are placed at the end, so I will have :

  • new_array = [5, 6, 1, 2, 3, 4]

CodePudding user response:

If I understand correctly you want to rotate the array.

array
# [1, 2, 3, 4, 5, 6]
array.rotate(2) # or array.rotate(array.index(3))
# [3, 4, 5, 6, 1, 2]

https://apidock.com/ruby/v2_5_5/Array/rotate

CodePudding user response:

Definitely use #rotate for this in actual use, but as an alternative, you could do something like #shift and #push until the desired element is at the beginning of the array.

def rotate(arr, elem)
    arr2 = arr.clone
    arr2.push(arr2.shift) until arr2.first == elem
    arr2
end
irb(main):026:0> arr = [1, 2, 3, 4, 5, 6]
=> [1, 2, 3, 4, 5, 6]
irb(main):027:0> rotate(arr, 3)
=> [3, 4, 5, 6, 1, 2]
irb(main):028:0> arr
=> [1, 2, 3, 4, 5, 6]
  • Related