带索引模的ruby排序依据
我有这个:带索引模的ruby排序依据,ruby,Ruby,我有这个: 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", "
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"]
为什么?如果查看
索引%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
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
[
<some permutation of "a" "d" "c" "b">,
<some permutation of "b" "a" "d" "c">,
<some permutation of "c" "b" "a" "d">,
]
如果按索引%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
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
[
<some permutation of "a" "d" "c" "b">,
<some permutation of "b" "a" "d" "c">,
<some permutation of "c" "b" "a" "d">,
]
由于Ruby中的排序不稳定,当您按索引%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
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
[
<some permutation of "a" "d" "c" "b">,
<some permutation of "b" "a" "d" "c">,
<some permutation of "c" "b" "a" "d">,
]
[
,
,
,
]
这就是你得到的。试试这个:
input.sort_by.with_index do |piece, index|
index%3 + (index.to_f / input.count)
end
我们是怎么来到这里的?
OP的解决方案很接近,但正如@sawa所提到的,索引%3
只给出了0、1或2。Ruby的不稳定排序会混淆这些组中的项目
不一定要这样。相反,我们可以伪造这些排序键,这样ruby就别无选择,只能正确排序。我们只需要一个模糊因素,即:
- 总是在增加,但是
- 始终足够小不会意外地将我们撞到一个新组(即<1)
索引:
input.sort_by.with_index do |piece, index|
index%3 + index
end
这可能看起来很愚蠢,但它确实符合1/2的标准:总是在增加,只是太大了。我们可以解决这个问题
第二集:红宝石救赎
我们知道index
,所以如果我们用input.count
将两边分开,我们得到index.to\u f/input.count它应该是index%4
另一种方法是input.to\u a.transpose.flatten
。你可以用result=index.sort
从input
到结果?我不确定我是否理解这个问题。。。