ruby sort_by with_index modulo

时间:2016-03-13 06:11:47

标签: ruby

我有这个:

.input-group-addon

我想要这个:

<form class="form-inline">
  <div class="form-group">
    <label class="sr-only" for="exampleInputAmount">Amount (in dollars)</label>
    <div class="input-group">
      <div class="input-group-addon">
        <select>
          <option>First</option> <!-- Replace it with images of your choice -->
          <option>Second</option>
        </select>
      </div>
      <input class="form-control" id="exampleInputAmount" placeholder="Amount" type="text">
      <div class="input-group-addon">.00</div>
    </div>
  </div>
  <button type="submit" class="btn btn-primary">Transfer cash</button>
</form>

我试过了:

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"]

为什么?

2 个答案:

答案 0 :(得分: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">,
]

这就是你得到的。

答案 1 :(得分: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别无选择,只能对其进行排序。我们只需要一个软糖因子:

  • 总是在增加,但
  • 总是足够小,不会意外地撞到我们的新组(即&lt; 1)

第一集:在黑暗中拍摄

考虑一下,用index来捏造它:

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

这可能看起来很愚蠢,但它确实符合1/2标准:总是增加,它只是大。我们可以解决这个问题。

第二集:Ruby Redemption

我们知道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