Joao Silva wrote in post #1067849:
a = [1 2 2 3 5 4 6 2 6 5 4]
I calculate the number that is repeated over and less repeats and if
possible to calculate something like this for example:
=> With 0 repeats found the number 1.3, etc.
=> With 1 repetition was found the number: 4, etc.
=> With 2 repetitions was found the number 5, etc.
Do it in steps. First count the number of times each value is seen:
a = [1, 2, 2, 3, 5, 4, 6, 2, 6, 5, 4]
counts = Hash.new(0)
a.each { |val| counts[val] += 1 }
# optional: counts = counts.sort_by { |val,count| count }
counts.each do |val,count|
puts "With #{count-1} repeats found the number #{val}"
end
This is a starting point. Then you can look at grouping together values
with the same count.
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
When you're clear what's happening here then you can look at the more
compact versions using group_by.
···
--
Posted via http://www.ruby-forum.com/\.