Reputation: 23
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.
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 :
Upvotes: 2
Views: 90
Reputation: 36496
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]
Clearly, if elem
is not in arr
, this will run forever. You could implement some kind of check to ensure this doesn't happen, but that's just one reason you shouldn't actually do this as anything other than a learning exercise.
One approach would be to find the index of elem
in arr
and shift/push that many times. The &.
operator may be useful in that situation to deal with the possibility of not finding elem
in arr
.
Upvotes: 3
Reputation: 136
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
Upvotes: 6