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 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 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 do you count the amout of duplicate characters in a string ruby
Possible solution:
string = "chineedne"
string.chars.uniq.count { |char| string.count(char) > 1 }
#=> 2
or without uniq
method to count total amount of duplicated characters:
string = "chineedne"
string.chars.count { |char| string.count(char) > 1 }
#=> 5
In order to get away from N**2 complexity, you also can use group_by
method for creating hash with character
-> array
that include all of this character from string
and than just use this hash to get any data that you want:
duplicates = string.chars.group_by { |char| char }.select { |key, value| value.size > 1 }
# or, for Ruby version >= 2.2.1 - string.chars.group_by(&:itself).select { |key, value| value.size > 1 }
than:
> duplicates.keys.size # .keys => ['n', 'e']
#=> 2
and
> duplicates.values.flatten.size # .values.flatten => ["n", "n", "e", "e", "e"]
#=> 5
Counting the number of repeated elements in an array
I would expect that something like this might work:
# in the controller (this returns a hash)
@locations = Country.joins(:user).order(:name).group(:name).count
# in your view
- @locations.each do |name, count|
%li
= name
= "(#{count})" if count > 1
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}
Related Topics
How to Use Bundler Behind a Proxy
How to Change the Default Path of View Files in a Rails 3 Controller
How to Use Define_Method to Create Class Methods
Rake "Already Initialized Constant Wfkv_" Warning
How to Match Something With Regex That Is Not Between Two Special Characters
How Does Array#Map Have Parameter to Do Something Like This
Best Way to Add Comments in Erb
How to Implement a Friendship Model in Rails 3 for a Social Networking Application
How to Get a Date from Date_Select or Select_Date in Rails
String Interpolation in Ruby Doesn't Work
Nomethoderror When Trying to Invoke Helper Method from Rails Controller
Checking If a Variable Is Defined in Sass