【问题标题】:How do you sort two arrays exactly the same?如何对两个完全相同的数组进行排序?
【发布时间】:2015-09-19 03:49:44
【问题描述】:

您将如何以相同的方式对两个数组进行排序?

hey = %w[e c f a d b g]
hoo = [1,2,3,4,5,6,7]
hey.sort      #=> [a,b,c,d,e,f,g]
hoo.same_sort #=> [4,6,2,5,1,3,7]

【问题讨论】:

  • 我猜这与哈希有关。

标签: arrays ruby sorting


【解决方案1】:

试一试:

hey.zip(hoo).sort
=> [["a", 4], ["b", 6], ["c", 2], ["d", 5], ["e", 1], ["f", 3], ["g", 7]]

hey.zip(hoo).sort.transpose
=> [["a", "b", "c", "d", "e", "f", "g"], [4, 6, 2, 5, 1, 3, 7]]

【讨论】:

    【解决方案2】:

    您可以使用Enumerable#sort_byArray#values_at 进行一次排序:

    sorted_indices = hey.each_index.sort_by { |i| hey[i] }
      #=> [3, 5, 1, 4, 0, 2, 6] 
    hey.values_at(*sorted_indices)
      #=> ["a", "b", "c", "d", "e", "f", "g"] 
    hoo.values_at(*sorted_indices)
      #=> [4, 6, 2, 5, 1, 3, 7] 
    

    【讨论】:

    • 我知道你会出现,我知道你会那样做。
    • @sawa,我想你会这样做的。
    猜你喜欢
    • 2012-04-03
    • 2011-07-15
    • 2013-06-09
    • 2014-07-22
    相关资源
    最近更新 更多