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