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}
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
Ruby count adjacent duplicate elements in array
%w[a b c a a b b c c c].chunk{|e| e}.map{|_, v| v.length}.max #=> 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, ....
Find a Duplicate in an array Ruby
Array#difference
comes to the rescue yet again. (I confess that @user123's answer is more straightforward, unless you pretend that Array#difference
is already a built-in method. Array#difference
is probably the more efficient of the two, as it avoids the repeated invocations of count
.) See my answer here for a description of the method and links to its use.
In a nutshell, it differs from Array#- as illustrated in the following example:
a = [1,2,3,4,3,2,4,2]
b = [2,3,4,4,4]
a - b #=> [1]
a.difference b #=> [1, 3, 2, 2]
One day I'd like to see it as a built-in.
For the present problem, if:
arr = [1,2,3,4,3,4]
the duplicate elements are given by:
arr.difference(arr.uniq).uniq
#=> [3, 4]
Array Count of repeating variable with integer output in ruby
So by the wording of the question, we only care about the number of occurrences for the string cat
:
array.count { |x| x == 'cat' }
=> 3
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
Related Topics
How to Keep the Delimiters When Splitting a Ruby String
How to Change My Ruby Version Using Rvm
Check If a String Contains Only Digits in Ruby
Difference Between "And" and && in Ruby
How to Avoid Nomethoderror For Missing Elements in Nested Hashes, Without Repeated Nil Checks
Redirect_To Using Post in Rails
Pg::Error: Select Distinct, Order by Expressions Must Appear in Select List
Error to Install Nokogiri on Osx 10.9 Maverick
Rescue_From Actioncontroller::Routingerror in Rails 4
Rails 3: Alias_Method_Chain Still Used
How to Run a Rake Task from Capistrano
Heroku Upload-Precompiling Assets Failed
How to Work With Two Different Databases in Rails With Active Records
Library Not Loaded: /Opt/Local/Lib/Libssl.1.0.0.Dylib (Loaderror)