2016-03-13 47 views
1

我有這樣的:紅寶石sort_by with_index模

input = ["a","b","c","d","a","b","c","d","a","b","c","d"] 

我想這一點:

result = ["a","a","a","b","b","b","c","c","c","d","d","d"] 

我嘗試這樣做:

input.sort_by.with_index do |piece, index| 
    index%3 
end 

我得到這個:

["a", "d", "c", "b", "c", "b", "d", "a", "d", "b", "a", "c"] 

爲什麼?

+2

它應該是'索引%4' –

+0

另一種方法是'input.each_slice(4).to_a.transpose.flatten'。 –

+0

你可以通過'result = index.sort'從'input'得到'result'嗎?不知道我明白這個問題... –

回答

2

如果看index % 3,您可以:

input  "a" "b" "c" "d" "a" "b" "c" "d" "a" "b" "c" "d" 
index  0 1 2 3 4 5 6 7 8 9 10 11 
index % 3 0 1 2 0 1 2 0 1 2 0 1 2 

,如果你組他們通過index % 3,您可以:

input  "a" "d" "c" "b" 
index % 3 0 0 0 0 

input  "b" "a" "d" "c" 
index % 3 1 1 1 1 

input  "c" "b" "a" "d" 
index % 3 2 2 2 2 

由於排序在Ruby中並不穩定,當您通過對它們進行排序index % 3,你得到:

[ 
    <some permutation of "a" "d" "c" "b">, 
    <some permutation of "b" "a" "d" "c">, 
    <some permutation of "c" "b" "a" "d">, 
] 

這就是你得到的。

0

試試這個:

input.sort_by.with_index do |piece, index| 
    index%3 + (index.to_f/input.count) 
end 

我們怎麼會在這裏?

OP的解決方案很接近,但正如@sawa所述,index%3僅給出0,1或2. Ruby的不穩定排序會混淆這些組中的項目。

它不一定是這樣。相反,可以對這些排序鍵進行欺騙,以便ruby別無選擇,只需對其進行排序即可。我們只需要一個軟糖因素是:

  • 一直增加,但
  • 總是足夠小,不會小心碰到我們進入一個新的組(即< 1)

首部曲:在黑暗中

一聲槍響考慮,通過index捏造它:

input.sort_by.with_index do |piece, index| 
    index%3 + index 
end 

這可能看起來很愚蠢,但它確實符合1/2標準:總是增加,這只是大。我們可以解決此問題。

情節二:Ruby的救贖

我們知道index < input.count,所以如果我們只是通過input.count分兩邊我們得到index.to_f/input.count <,這正是我們想要的(但不要忘了轉換成浮動) !

input.sort_by.with_index do |piece, index| 
    index%3 + (index.to_f/input.count) 
end 

獎金

我認爲這個解決方案是聰明的,但正是由於這個原因,公衆實際上並不使用它:

input.sort_by.with_index do |piece, index| 
    index%3 - 1.to_f/(1 + index) 
end