【问题标题】:Sort an array of array by 2 conditions按 2 个条件对数组数组进行排序
【发布时间】:2017-09-28 19:53:36
【问题描述】:

我必须对此进行排序

ary = [[5, "e", "2"], [2, "r", "="], [2, "y", "2"], [2, "h", "="]]

获得:

# => [[5, "e", "2"], [2, "y", "2"], [2, "h", "="], [2, "r", "="]] 

如果最后一个元素(索引 2)等于“=”,则它必须在具有相同第一个元素的数组之后,即使字母在前面。 像这样:

ary.each_with_index do |array, index|
  if ary[index][2] == "=" && ary[index][0] == ary[index +1][2]
    a = ary[index]
    b = ary[index +1]
    ary[index] = b
    ary[index+1] = a
  end
end

【问题讨论】:

  • 查看带有“=”的元素,是否要对第一个元素进行降序排序?当有关系时,按第二个元素的升序排序?没有"="的元素也一样? ary = [[2, "e", "2"], [2, "e", "10"]]呢?请通过编辑(而不是发表评论)来澄清。

标签: arrays ruby sorting


【解决方案1】:

我假设,对于以"=" 结尾的元素,排序是通过减少第一个元素(整数)的值来排序,当有关系时,通过增加第二个元素(字符串)的顺序。此外,我假设不以"=" 结尾的元素的排序是相同的,除非前两个元素都打成平手,排序是通过增加最后一个元素(字符串)的顺序来进行的。

def sort_em(arr)
  arr.sort_by { |n, s1, s2| [s2 == "=" ? 1 : 0, -n, s1, s2] }
end

sort_em [[5, "e", "2"], [2, "r", "="], [2, "y", "2"], [2, "h", "="]]
  #=> [[5, "e", "2"], [2, "y", "2"], [2, "h", "="], [2, "r", "="]]

请参阅Array#<=> 文档的第三段,了解排序时数组的排序方式。

为了确保以"=" 结尾的元素在排序中排在最后,我只是在sort_by 的块中的数组开头添加了1 (0),用于数组结尾(不结尾)为"="

【讨论】:

    【解决方案2】:

    您可以使用sort 并提供您自己的块进行排序:

    ary.sort do |a, b| 
      if a[2] == '=' && b[2] != '='
        # a has '=' => a > b 
        1
      elsif b[2] == '=' && a[2] != '='
        # b has '=' => a < b 
        -1
      else
        # This is hit if neither a nor b have a '=' OR when both do.
        # Use default comparison operator
        # but restrict it to the second element of the array
        a[1] <=> b[1]
      end
    end
    

    该块需要返回一个值为1-10。在此基础上,按顺序排列值。

    • 1: a > b
    • -1:一个
    • 0: a = b

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-16
      • 2019-11-09
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多