Reorder Array of Integers Around Key Integer

I have up to 7 integers representing each day of the week 0 ... 6 (sun - sat)

The current day = 3 (wednesday).

How can I reorder array of integers so that the number closest to Wednesday ( 3 ) comes first.

For example:

Current Day = 3
Days (input) = [0, 1, 2, 3, 4, 5, 6]
Correct Output = [3, 4, 5, 6, 0, 1, 2]

But the array may not contain all days (for example current day might be missing):

Current Day = 3
Days (input) = [0, 2, 4, 6]
Correct Output = [4, 6, 0, 2]

Basically reorder the array so that the current day comes first (or the integer that preceeds it)

Current Attempt: I've looked into using a.rotate but I'm unsure how to deal with if the current day is not in the array.

I've also tried using min_by but it does not loop integers

@days.min_by { |x| (x.to_f - Time.now.wday).abs } 

If you're looking for the days that come after the current day:

my_array.sort_by{|x| (x-current_day)%7}

If all you are looking for is the first number, simply use min_by instead of sort_by

And with your input:

irb(main):059:0* my_array = [0, 1, 2, 3, 4, 5, 6]
=> [0, 1, 2, 3, 4, 5, 6]
irb(main):060:0> current_day = 3
=> 3
irb(main):061:0> my_array.sort_by{|x| (x-current_day)%7}
=> [3, 4, 5, 6, 0, 1, 2]
irb(main):062:0> my_array = [0, 2, 4, 6]
=> [0, 2, 4, 6]
irb(main):063:0> my_array.sort_by{|x| (x-current_day)%7}
=> [4, 6, 0, 2]

All you need to do is find the index of the integer that preceeds input current day, if it itself is not included in the array. Here:

def mrotate(days, c_day)
  index = days.index(c_day)
  index = days.index(days.find { |d| d > c_day}) if !index
  days.rotate index || 0
end

mrotate([0, 1, 2, 3, 4, 5, 6], 3)
#=> [3, 4, 5, 6, 0, 1, 2]

mrotate([0, 2, 4, 6], 3)
#=> [4, 6, 0, 2]

您可以搜索>= 3的第一个索引,并将数组拆分为两部分:

x = [0, 1, 2, 3, 4, 5, 6]
y = [0, 2, 4, 6]
pos = x.index{|s| s >= 3}
# => 3
x[pos..-1] + x[0..pos-1]
# [3, 4, 5, 6, 0, 1, 2]
pos = y.index{|s| s >= 3}
# => 2
y[pos..-1] + y[0..pos-1]
# => [4, 6, 0, 2]
链接地址: http://www.djcxy.com/p/25694.html

上一篇: 如果VARIABLE在ARRAY ruby​​中

下一篇: 按键整数重新排序整数数组