Skip to content

Instantly share code, notes, and snippets.

@zalom
Last active May 9, 2016 08:26
Show Gist options
  • Save zalom/380d5bdca5d46da9e554ea16d15b876c to your computer and use it in GitHub Desktop.
Save zalom/380d5bdca5d46da9e554ea16d15b876c to your computer and use it in GitHub Desktop.
Coding Test - Return a number of distinct values that occur two or more times in an array
# Count occurrences
# FIND DESCRIPTION BELOW THE CODE
def countDuplicates array
puts array.select{|x| array.count(x) > 1}
.each_with_object(Hash.new(0)) {|num,counts| counts[num] += 1}
.each_value.to_a.uniq
end
# Usage
# countDuplicates([1,3,1,4,5,6,3,2,4,4,6,7,6,7,8,8,9,7,7]);
# countDuplicates(%w(how much wood would a wood chuck chuck chuck));
# DESCRIPTION
# Write a program to find the total number of duplicate elements in any array.
# We want the number of distinct values that occur two or more times, not the number of occurrences.
# Complete the function "countDuplicates" which contains an integer array "numbers" as its argument.
# Return an integer which denotes the required result.
# Constraints:
# 1 ≤ size of array ≤ 1000
# 1 ≤ numbers[i] ≤ 1000
# Input Format:
# * Function "countDuplicates" contains an integer array "numbers" as its argument.
# Output Format:
# * Return an integer which denotes the required result.
# Sample Input #00:
# 1
# 3
# 1
# 4
# 5
# 6
# 3
# 2
# Sample Output #00:
# 2
# Explanation #00:
# * The input gives you: > array[8] = {1,3,1,4,5,6,3,2}.
# * The number of duplicate elements in the array is 2, because 1 and 3 both occur more than once.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment