2

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]
1
  • 1
    Using Array#rotate, as suggested by @Ceribe, would be the Ruby way, but you could also write arr = [1, 2, 3, 4, 5, 6]; n = arr.size; arr.each_index.map { |i| arr[(i+2) % n] } #=> [3, 4, 5, 6, 1, 2]. Commented Mar 7, 2022 at 0:49

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yes. But 2 isn't an input. So array.rotate(3-1) or array.rotate(array.index(3)), then, right?
Yes, I was just explaining how rotate works. To make "3" the first element it should be done as you said.
3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.