“自然”排序Ruby中的数组

时间:2021-09-16 16:00:37

I have an array which contains numbers and alphabets something like:

我有一个包含数字和字母的数组

newArray = ["1 a", "1 b" ,"2 c", "2 a"]

newArray = ["1 a", "1 b","2 c", "2 a"]

I would like to sort them in a way that the output is expected as follows:

我想以期望输出的方式对它们进行排序如下:

newArray = ["2 a", "2 c" ,"1 a", "1 b"]

newArray = [" 2a ", " 2c ", " 1a ", " 1b "]

What I want to do is sort the numbers in descending order and if the numbers are same, then sort alphabetically

我要做的是按降序对数字排序,如果数字相同,那么按字母排序

Can I implement a comparison function in sort_by or is there a way to do that using ruby sort

我能在sort_by中实现一个比较函数吗?还是有办法使用ruby排序来实现

3 个解决方案

#1


7  

First you should use a better representation of your input. You can parse your existing array for example like this:

首先,应该更好地表示输入。您可以解析现有的数组,例如:

arr = newArray.map { |s| x,y = s.split; [x.to_i, y] }
# => [[1, "a"], [1, "b"], [2, "c"], [2, "a"]]

Then we can sort as we wish using sort_by:

然后我们可以使用sort_by进行排序:

arr.sort_by { |x,y| [-x, y] }
# => [[2, "a"], [2, "c"], [1, "a"], [1, "b"]]

#2


2  

Similar to @NiklasB. 's answer above (copied his sort_by)

类似于@NiklasB。上面的答案(复制了他的sort_by)

arr.map(&:split).sort_by { |x,y| [-x.to_i, y] }

=> [["2", "a"], ["2", "c"], ["1", "a"], ["1", "b"]]

#3


0  

In a less elegant way, you can do that

用一种不那么优雅的方式,你可以做到。

    arr.sort! do |p1, p2|
      num1, str1 = p1.split(' ')
      num2, str2 = p2.split(' ')
      if (num1 != num2)
        p2 <=> p1
      else
        p1 <=> p2
      end
    end
    $stdout.puts arr

#1


7  

First you should use a better representation of your input. You can parse your existing array for example like this:

首先,应该更好地表示输入。您可以解析现有的数组,例如:

arr = newArray.map { |s| x,y = s.split; [x.to_i, y] }
# => [[1, "a"], [1, "b"], [2, "c"], [2, "a"]]

Then we can sort as we wish using sort_by:

然后我们可以使用sort_by进行排序:

arr.sort_by { |x,y| [-x, y] }
# => [[2, "a"], [2, "c"], [1, "a"], [1, "b"]]

#2


2  

Similar to @NiklasB. 's answer above (copied his sort_by)

类似于@NiklasB。上面的答案(复制了他的sort_by)

arr.map(&:split).sort_by { |x,y| [-x.to_i, y] }

=> [["2", "a"], ["2", "c"], ["1", "a"], ["1", "b"]]

#3


0  

In a less elegant way, you can do that

用一种不那么优雅的方式,你可以做到。

    arr.sort! do |p1, p2|
      num1, str1 = p1.split(' ')
      num2, str2 = p2.split(' ')
      if (num1 != num2)
        p2 <=> p1
      else
        p1 <=> p2
      end
    end
    $stdout.puts arr