A = ['o', 'i', 's', 'm']
words = ["dinosaur", "dosimetry", "moist", "personal", "since",
"including", "guide", "shop", "directory", "board", "location",
"change", "white", "text", "small", "emotions", "rating",
"rate", "movies", "government"]
Вот два метода, которые возвращают слова в words
, которые содержат все буквы, содержащиеся в A
.
# 1
def select_some(words)
words.select { |word| A & word.chars == A }
end
select_some(words)
#=> ["dosimetry", "moist", "emotions", "movies"]
Оперативная строка может быть изменена на
words.select { |word| (A-str.chars).empty? }
# 2
n = 1
H = A.each_with_object({}) do |c,h|
h[c] = n
n <<= 1
end
#=> {"s"=>1, "i"=>2, "o"=>4, "m"=>8}
N = n - 1
#=> 15
def select_some(words)
words.select do |word|
n = 0
word.each_char do |c|
x = H[c]
n |= x if x
end
n == N
end
end
select_some(words)
#=> ["dosimetry", "moist", "emotions", "movies"]