2

If I start with a contiguous sequence of dates:

(Date.today..(Date.today + 30)).to_a

How can I sort this array so that all dates, in sequence, are at least 1 day apart?

I realise that this would of course not be possible for an array of 2 contiguous dates.

4

4 回答 4

2
(1..6).partition(&:odd?).flatten #=>[1, 3, 5, 2, 4, 6]

无论偶数或奇数元素如何,都适用于范围(或任何可枚举)。

于 2012-09-10T21:11:19.563 回答
2

这对我有用:

dates = (Date.today..(Date.today + 30)).to_a
dates.each_with_index{|d,i| dates.push(dates.delete(d)) if i % 2}
于 2012-09-10T18:45:02.527 回答
2

数组的长度是否总是偶数?是这样,我会简单地写(如果需要,很容易修改为奇数长度):

>> (1..6).each_slice(2).to_a.transpose.flatten(1)
=> [1, 3, 5, 2, 4, 6]
于 2012-09-10T19:38:05.407 回答
-1

愚蠢的解决方案:

dates = (Date.today..(Date.today + 30)).to_a
begin
  ary   = dates.shuffle
  valid = (ary.select.each_with_index { |element, i| 
    ( i == ary.length-1 || (ary[i+1]  - element).abs  > 1 ) &&
    ( i == 0            || (element   - ary[i-1]).abs > 1 )
  })
end until valid.length == dates.length
ary

仅在您不太关心性能时才使用;-)

于 2012-09-10T19:05:21.147 回答