Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count duplicates in Ruby Arrays

People also ask

How do you check if there are duplicates in an array Ruby?

select { array. count } is a nested loop, you're doing an O(n^2) complex algorithm for something which can be done in O(n). You're right, to solve this Skizit's question we can use in O(n); but in order to find out which elements are duplicated an O(n^2) algo is the only way I can think of so far.

How do you count duplicates in array?

To count the duplicates in an array:Declare an empty object variable that will store the count for each value. Use the forEach() method to iterate over the array. On each iteration, increment the count for the value by 1 or initialize it to 1 .

How do you count elements in an array Ruby?

Ruby | Array count() operation Array#count() : count() is a Array class method which returns the number of elements in the array. It can also find the total number of a particular element in the array. Syntax: Array. count() Parameter: obj - specific element to found Return: removes all the nil values from the array.

What is .first in Ruby?

first is a property of an array in Ruby that returns the first element of an array. If the array is empty, it returns nil. array. first accesses the first element of the array, i.e., the element at index 0 .


Another version of a hash with a key for each element in your array and value for the count of each element

a = [ 1, 2, 3, 3, 4, 3]
h = Hash.new(0)
a.each { | v | h.store(v, h[v]+1) }

# h = { 3=>3, 2=>1, 1=>1, 4=>1 } 

Given:

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

My favourite way of counting elements is:

counts = arr.group_by{|i| i}.map{|k,v| [k, v.count] }

# => [[1, 1], [2, 2], [3, 2], [4, 1], [5, 1]]

If you need a hash instead of an array:

Hash[*counts.flatten]

# => {1=>1, 2=>2, 3=>2, 4=>1, 5=>1}

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}

Simple.

arr = [2,3,4,3,2,67,2]
repeats = arr.length - arr.uniq.length
puts repeats