Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether a string contains all the characters of another string in Ruby

Tags:

string

ruby

Let's say I have a string, like string= "aasmflathesorcerersnstonedksaottersapldrrysaahf". If you haven't noticed, you can find the phrase "harry potter and the sorcerers stone" in there (minus the space).

I need to check whether string contains all the elements of the string.

string.include? ("sorcerer") #=> true
string.include? ("harrypotterandtheasorcerersstone") #=> false, even though it contains all the letters to spell harrypotterandthesorcerersstone

Include does not work on shuffled string.

How can I check if a string contains all the elements of another string?

like image 985
Iggy Avatar asked Aug 29 '16 18:08

Iggy


People also ask

How do you check if a string contains a number Ruby?

You can use the String class's =~ method with the regex /\d/ as the argument.

How do you find the part of a string in Ruby?

Accessing Characters Within a String To print or work with some of the characters in a string, use the slice method to get the part you'd like. Like arrays, where each element corresponds to an index number, each of a string's characters also correspond to an index number, starting with the index number 0.

What does chars do in Ruby?

chars is a String class method in Ruby which is used to return an array of characters in str. Returns: An array of the characters.


1 Answers

Sets and array intersection don't account for repeated chars, but a histogram / frequency counter does:

require 'facets'

s1 = "aasmflathesorcerersnstonedksaottersapldrrysaahf"
s2 = "harrypotterandtheasorcerersstone"
freq1 = s1.chars.frequency
freq2 = s2.chars.frequency
freq2.all? { |char2, count2| freq1[char2] >= count2 } 
#=> true

Write your own Array#frequency if you don't want to the facets dependency.

class Array
  def frequency
    Hash.new(0).tap { |counts| each { |v| counts[v] += 1 } }
  end
end
like image 99
tokland Avatar answered Sep 18 '22 22:09

tokland