Ruby: How to Find Non-Unique Elements in Array and Print Each with Number of Occurrences

ruby: how to find non-unique elements in array and print each with number of occurrences?

puts a.uniq.
map { | e | [a.count(e), e] }.
select { | c, _ | c > 1 }.
sort.reverse.
map { | c, e | "#{e}:#{c}" }

How to find number of identical elements in array in ruby language

To get a number of non-uniq elements:

a.size - a.uniq.size
#=> 1

To get a count of non-uniq elements:

a.chunk(&:itself).reject { |chunk| chunk.last.one? }.flat_map(&:last).size
#=> 2

Acording to the edited question:

'There are ' + a.chunk(&:itself).reject { |chunk| chunk.last.one? }.map {|chunk| "#{chunk.last.size} \"#{chunk.first}\"" }.join(' and ') + 'in array.'
#=> "There are 2 "2" in array."

If there were more duplicated entries:

a = [1,1,2,2,3,3,3,4]

the output would look like:

There are 2 "1" and 2 "2" and 3 "3"in array.

How to count identical string elements in a Ruby array

names = ["Jason", "Jason", "Teresa", "Judah", "Michelle", "Judah", "Judah", "Allison"]
counts = Hash.new(0)
names.each { |name| counts[name] += 1 }
# => {"Jason" => 2, "Teresa" => 1, ....

How to count duplicate elements in a Ruby array

The following code prints what you asked for. I'll let you decide on how to actually use to generate the hash you are looking for:

# sample array
a=["aa","bb","cc","bb","bb","cc"]

# make the hash default to 0 so that += will work correctly
b = Hash.new(0)

# iterate over the array, counting duplicate entries
a.each do |v|
b[v] += 1
end

b.each do |k, v|
puts "#{k} appears #{v} times"
end

Note: I just noticed you said the array is already sorted. The above code does not require sorting. Using that property may produce faster code.

How to find and return a duplicate value in array

a = ["A", "B", "C", "B", "A"]
a.detect{ |e| a.count(e) > 1 }

I know this isn't very elegant answer, but I love it. It's beautiful one liner code. And works perfectly fine unless you need to process huge data set.

Looking for faster solution? Here you go!

def find_one_using_hash_map(array)
map = {}
dup = nil
array.each do |v|
map[v] = (map[v] || 0 ) + 1

if map[v] > 1
dup = v
break
end
end

return dup
end

It's linear, O(n), but now needs to manage multiple lines-of-code, needs test cases, etc.

If you need an even faster solution, maybe try C instead.

And here is the gist comparing different solutions: https://gist.github.com/naveed-ahmad/8f0b926ffccf5fbd206a1cc58ce9743e

How do I detect duplicate values within an array in Ruby?

You can create a hash to store number of times any element is repeated. Thus iterating over array just once.

h = Hash.new(0)
['a','b','b','c'].each{ |e| h[e] += 1 }

Should result

 {"a"=>1, "b"=>2, "c"=>1}

How to count duplicates in Ruby Arrays

This will yield the duplicate elements as a hash with the number of occurences for each duplicate item. Let the code speak:

#!/usr/bin/env ruby

class Array
# monkey-patched version
def dup_hash
inject(Hash.new(0)) { |h,e| h[e] += 1; h }.select {
|k,v| v > 1 }.inject({}) { |r, e| r[e.first] = e.last; r }
end
end

# unmonkeey'd
def dup_hash(ary)
ary.inject(Hash.new(0)) { |h,e| h[e] += 1; h }.select {
|_k,v| v > 1 }.inject({}) { |r, e| r[e.first] = e.last; r }
end

p dup_hash([1, 2, "a", "a", 4, "a", 2, 1])
# {"a"=>3, 1=>2, 2=>2}

p [1, 2, "Thanks", "You're welcome", "Thanks",
"You're welcome", "Thanks", "You're welcome"].dup_hash
# {"You're welcome"=>3, "Thanks"=>3}

How to find an item in array which has the most occurrences

First build a hash mapping each value in the array to its frequency…

arr = [1, 1, 1, 2, 3]

freq = arr.inject(Hash.new(0)) { |h,v| h[v] += 1; h }
#=> {1=>3, 2=>1, 3=>1}

… then use the frequency table to find the element with the highest frequency:

arr.max_by { |v| freq[v] }
#=> 1

Ruby: Count unique elements and their occurences in an array

['A','A','A','A','B','B','C'].group_by{|e| e}.map{|k, v| [k, v.length]}.to_h

how to get the indexes of duplicating elements in a ruby array

 duplicates = arr.each_with_index.group_by(&:first).inject({}) do |result, (val, group)|
next result if group.length == 1
result.merge val => group.map {|pair| pair[1]}
end

This will return a hash where the keys will be the duplicate elements and the values will be an array containing the index of each occurrence.
For your test input, the result is:

{"A"=>[0, 6], "X"=>[1, 2]}

If all your care about is the indices you can do duplicates.values.flatten to get an array with just the indices.
In this case: [0, 6, 1, 2]



Related Topics



Leave a reply



Submit