On Mon, Jul 9, 2012 at 9:14 AM, Jesús Gabriel y Galán
<[email protected]> wrote:
> On Sun, Jul 8, 2012 at 10:13 PM, Joao Silva <[email protected]> wrote:
>> Brian Candler wrote in post #1067902:
>>
>>> a = [1, 2, 2, 3, 5, 4, 6, 2, 6, 5, 4]
>>> counts = Hash.new(0)
>>> a.each { |val| counts[val] += 1 }
>>> groups = {}
>>> counts.each do |val,count|
>>> groups[count] ||= []
>>> groups[count] << val
>>> end
>>> groups.each do |count,vals|
>>> puts "With #{count-1} repeats found #{vals.sort.join(", ")}"
>>> end
>>>
>>
>> One last thing, how do I print the results that I stay in order, because
>> the above code prints:
>>
>> With 0 repeats found 1, 3
>> With 2 repeats found 2
>> With 1 repeats found 4, 5, 6
>>
>> and I seek it to print in order:
>
> groups.sort.each do |count,vals|
> puts "With #{count-1} repeats found #{vals.sort.join(", ")}"
> end
Alternative solution
irb(main):001:0> a = [1, 2, 2, 3, 5, 4, 6, 2, 6, 5, 4]
=> [1, 2, 2, 3, 5, 4, 6, 2, 6, 5, 4]
irb(main):002:0> max=0; counts = a.inject(Hash.new(0)) {|c, x|
cc=(c[x]+=1); max=cc if cc>max; c}
=> {1=>1, 2=>3, 3=>1, 5=>2, 4=>2, 6=>2}
irb(main):003:0> 1.upto(max){|r| printf "With %d repeats: %p\n", r,
counts.select {|k,v| v==r}.map{|k,v|k} }
With 1 repeats: [1, 3]
With 2 repeats: [5, 4, 6]
With 3 repeats: [2]
=> 1
(Explanation omitted for pedagogical reasons.)
Have fun!
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
-- You received this message because you are subscribed to the Google Groups
ruby-talk-google group. To post to this group, send email to
[email protected]. To unsubscribe from this group, send email
to [email protected]. For more options, visit this
group at https://groups.google.com/d/forum/ruby-talk-google?hl=en