I wrote a program to get and calculate non-overlapping elements in an array. If you want something that is duplicated, you can get it by changing the description of the comparison operator. I would appreciate it if you could point out any mistakes in the recognition.
--Practice --Problem --Answer
--References
Create a method that outputs the sum of any three numbers. However, if the same number is included, it is not counted.
The hash is generated first because we want to calculate the number of elements and use select
to get the one that meets the conditions.
def uniq_num(ary)
counts = Hash.new(0) #Generate hash
ary.each { |v| counts[v] += 1 } #Search for duplicate elements
i = counts.select { |v, count| count == 1 }.keys #Get only non-duplicates
p i.sum #Output total
end
#Method call
uniq_num([1, 2, 3])
uniq_num([3, 2, 3])
uniq_num([3, 3, 3])
#Terminal output result
# 6
# 2
# 0
-Ruby 3.0.0 Reference Manual (Hash.new) -Ruby 3.0.0 Reference Manual (filter) -Remove duplicate elements from Ruby array -[How can I efficiently extract repeating elements in a Ruby array? Duplicate
Recommended Posts