Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,563 questions

56,781 answers

573 users

How to find the element with minimum occurrences in an array with Ruby

1 Answer

0 votes
# Finds the element with the minimum occurrences in an array.
#
# @param array [Array] The input array to process.
# @return [Object, nil] The least frequent element, or nil if array is empty.
def min_occurrence(array)
  return nil if array.nil? || array.empty?

  # 1. tally counts occurrences into a Hash: { 1=>3, 3=>4, 4=>3, 5=>2, 2=>3 } (Ruby 2.7+)
  # 2. min_by extracts the key-value pair [element, count] with the lowest count
  # 3. .first gets the element key from that tuple
  array.tally.min_by { |_element, count| count }&.first
end

# Example usage:
arr = [1, 3, 1, 1, 4, 4, 5, 5, 4, 2, 2, 2, 3, 3, 3]

result = min_occurrence(arr)

if result
  puts result # Output: 5
else
  puts 'The array was empty.'
end



# run:
#
# 5
#

 



answered Sep 26 by avibootz
...