Kirill Zhuravlov
Kirill Zhuravlov

Reputation: 464

Return array with duplicated elements only N times maximum for duplicated elements ruby

How can I return array with duplicated elements from given array that contains each number of duplicated elements only max_elements times without reordering.

def delete_nth_elements(array,max_elements)
  #your code here
end

delete_nth_elements([1,2,3,4,1,2,3,5,1,2,3,6],2) # return [1,2,3,4,1,2,3,5,6]

and drop the next [1,2,3] since this would lead to 1 2 and 3 being in the result 3 times.

Upvotes: 0

Views: 47

Answers (1)

Cary Swoveland
Cary Swoveland

Reputation: 110675

def delete_nth_elements(arr, max_elements)
  h = Hash.new(0)
  arr.select { |e| (h[e] += 1) <= max_elements}   
end

delete_nth_elements([1,2,3,4,1,2,3,5,1,2,3,6],2)
  #=> [1,2,3,4,1,2,3,5,6]

h is often called a counting hash. See Hash::new, particularly in reference to the default value (here 0). One could instead write

def delete_nth_elements(arr, max_elements)
  h = {}
  arr.select { |e| (h[e] ||= 0) += 1) <= max_elements}   
end

h[e] ||= 0) += 1 expands to

(h[e] = h[e] || 0) += 1

If h does not have a key e, h[e] #=> nil, so the above expression reduces to

h[e] = 0 + 1
  #=> 1

Upvotes: 3

Related Questions