将范围和计数的散列中的整数数组分组

时间:2016-08-01 05:49:09

标签: arrays ruby hash grouping

我有一个这样的整数数组:

  [1, 1, 1, 2, 2, 4, 4, 5, 6, 11, 11, 12, 15, 22, 23, 23, 23, 31, 32, 32]

我正在尝试将其转换为哈希值,按照范围分组,间隔为10 ....

所以,在这种情况下,它将是

{ [1..10] => 9, [11..20] => 4, [21..30] => 4, [31..40] => 3 }

我尝试了一些尚未接近的事情,所以把它们放在这里有点无意义。我可以将数组转换为范围

  [1, 1, 1, 2, 2, 4, 4, 5, 6, 11, 11, 12, 15, 22, 23, 23, 23, 31, 32, 32].sort.uniq.inject([]) do |spans, n|
    if spans.empty? || spans.last.last != n - 1
      spans + [n..n]
    else
      spans[0..-2] + [spans.last.first..n]
    end
   end

但这不是我要找的。有什么建议吗?

3 个答案:

答案 0 :(得分:3)

Hash[
  your_array.group_by{|i| i / 10}.map{|k,v|
    [(k*10+1..(k+1)*10), v.count]
  }
]
#=> {1..10=>9, 11..20=>4, 21..30=>4, 31..40=>3}

答案 1 :(得分:3)

arr.each_with_object(Hash.new(0)) do |e, hash|
  i = e / 10
  hash[i*10+1..i*10+10] += 1
end
#⇒ {
#    1..10 => 9,
#   11..20 => 4,
#   21..30 => 4,
#   31..40 => 3
# }

答案 2 :(得分:2)

我已将示例修改为21到30之间没有数字,因此哈希应包含键值对21..30=>0

arr = [1, 1, 1, 2, 2, 4, 4, 5, 6, 11, 11, 12, 20, 32, 33, 33, 33, 41, 42, 42]

intervals = (1..arr.last-1).step(10).each_with_object({}) { |n,h| h[n..n+9] = 0 }
  #=> {1..10=>0, 11..20=>0, 21..30=>0, 31..40=>0, 41..50=>0}

arr.each_with_object(intervals) do |n,intervals|
  interval_end = 10*((n+9)/10)     
  intervals[interval_end-9..interval_end] += 1
end
  #=> {1..10=>9, 11..20=>4, 21..30=>0, 31..40=>4, 41..50=>3}