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

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

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,709 questions

55,473 answers

573 users

How to get common letters that appear in every word in a list of words with Ruby

1 Answer

0 votes
require 'set'

=begin
    Efficient algorithm using Ruby Sets:
    -----------------------------------
    Each word is converted into a Set of its unique characters.

    Example:
        "algebraic" -> #<Set: {'a','l','g','e','b','r','i','c'}>

    Then:
        - Start with the set of letters from the first word.
        - Intersect with each subsequent word's letter set.
        - The final set contains letters common to all words.

    This uses Ruby's built-in:
        - Set
        - & (set intersection)
        - map, each, and functional decomposition
=end


# Convert a word into a Set of its unique letters
def letters_of(word)
  Set.new(word.chars)
end


# Compute letters common to all words
def common_letters(words)
  return Set.new if words.empty?

  # Start with letters of the first word
  common = letters_of(words.first)

  # Intersect with each subsequent word
  words.drop(1).each do |word|
    current = letters_of(word)
    common &= current   # Ruby's built-in set intersection
  end

  common
end


# Print letters in sorted order
def print_letters(letters)
  puts letters.to_a.sort.join(" ")
end


# Main program
words = [
  "algebraic",
  "alphabetic",
  "ambiance",
  "abacus",
  "metabolic",
  "parabolic",
  "playback",
  "drawback",
  "fabricate",
  "flashback",
  "syllabic"
]

result = common_letters(words)

puts "Common letters across all words:"
print_letters(result)



=begin
run:

Common letters across all words:
a b c

=end

 



answered Jul 10 by avibootz

Related questions

...