根据ruby中出现的次数对数组进行排序

时间:2012-05-01 12:42:07

标签: ruby arrays sorting

我希望这个整数数组根据其出现次数按正确的顺序排序。

question = [[1, 7, 8, 9, 10, 11, 12, 19, 20, 21, 31, 32, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 81, 129, 132, 133, 134, 135, 136, 139], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 29, 31, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 81, 129, 130, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141], [30], [77]] 

question.flatten.uniq.size = 90

answer = sort_it(question)

answer = [77, 68, 8, 9, 10, 11, 12, 19, 20, 21, 31, 139, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 135, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 136, 66, 67, 7, 70, 71, 72, 73, 74, 75, 76, 1, 78, 79, 81, 129, 132, 133, 134, 45, 65, 32, 2, 3, 4, 5, 6, 13, 14, 15, 16, 17, 22, 23, 24, 25, 26, 27, 29, 33, 41, 69, 130, 137, 138, 140, 141, 30]

answer.uniq.size = 90

这是我的Ruby代码:

def sort_it(actual)
        join=[]
        buffer = actual.dup 
        final = [ ]

                (actual.size-2).downto(0) {|j|
                join.unshift(actual.map{|i| i }.inject(:"&"))
                actual.pop
                }
        ordered_join =  join.reverse.flatten
        final << ordered_join
        final << buffer.flatten - ordered_join

        final.flatten
end

这种方法可以吗?有更有效的方法吗?

编辑:

为了向tokland和niklas致敬,编辑了以前错误顺序的答案。 谢谢!

2 个答案:

答案 0 :(得分:4)

使用group_by

question.flatten.group_by{|x| x}.sort_by{|k, v| -v.size}.map(&:first)

答案 1 :(得分:0)

回答sort_by {| k,v |每次比较元素时,-v.size}都会调用v.size。更有效的解决方案:

question.flatten.group_by(&:to_i).map{|k,v| [k, -v.size]}.sort_by(&:last).map(&:first)

虽然阵列的大小很容易获得,但是这是不必要的费用(O(排序算法)而不是O(n)),这个习惯用于更昂贵的操作无论如何都要好好记住