Created
November 20, 2010 13:12
-
-
Save michel/707811 to your computer and use it in GitHub Desktop.
Alphabet in substring?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby -wKU | |
# Say you have one string of alphabetic characters, and say you have another, | |
# guaranteed smaller string of alphabetic characters. Algorithmically speaking, | |
# what's the fastest way to find out if all the characters in the smaller string are in the larger string? | |
# | |
# For example, if the two strings were: | |
# | |
# | |
# String 1: ABCDEFGHLMNOPQRS | |
# String 2: DCGSRQPOM | |
# | |
# | |
# You'd get true as every character in string2 is in string1. If the two strings were: | |
# | |
# | |
# String 1: ABCDEFGHLMNOPQRS | |
# String 2: DCGSRQPOZ | |
# | |
# | |
# you'd get false as Z isn't in the first string. | |
# Cool Solution | |
#"What if - given that we have a limited range of possible characters. | |
# I assigned each character of the alphabet to a prime number starting with 2 and going up from there. | |
# So A would be 2, and B would be 3, and C would be 5, etc. | |
# And then I went through the first string and 'multiplied' each character's prime number together. | |
# You'd end up with some big number right? | |
# And then - what if I iterated through the 2nd string and 'divided' by every character in there. If any division gave a remainder. | |
# You knew you didn't have a match. If there was no remainders through the whole process, you knew you had a subset. | |
require 'test/unit' | |
require 'mathn' | |
class TestSubString < Test::Unit::TestCase | |
def test_table_generator | |
assert generate_table("a".."z")["a"] == 2 | |
assert generate_table["c"] == 5 | |
end | |
def test_chars_in_aphabet? | |
assert chars_in_alphabet?("ABCDEFGHLMNOPQRS","DCGSRQPOM") | |
assert !chars_in_alphabet?("ABCDEFGHLMNOPQRS","DCGSRQPOZ") | |
end | |
end | |
def generate_table(alphabet = [("a".."z").to_a,("A".."Z").to_a].flatten) | |
alphabet.to_a.inject([Prime.new,{}]) { |p,n| [p[0],p[1].merge(n => p[0].succ)] }[1] | |
end | |
def chars_in_alphabet?(alphabet,str) | |
table = generate_table | |
product = alphabet.split("").inject(1){|p,n| table[n] * p } | |
return !str.split("").any? { |i| (product % table[i]) > 0 } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment