Last active
June 1, 2018 18:22
-
-
Save marksiemers/7a10adc059f2c1909447c96b12aad2c8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
require 'benchmark/ips' | |
class PangramArraySubtraction | |
def self.pangram?(phrase) | |
([*'a'..'z'] - phrase.downcase.chars).empty? | |
end | |
end | |
class PangramArrayAllInclude | |
def self.pangram?(phrase) | |
phrase.downcase.chars.all?(&('a'..'z').method(:include?)) | |
end | |
end | |
class PangramAllSquareBrackets | |
def self.pangram?(phrase) | |
('a'..'z').all?(&phrase.downcase.method(:[])) | |
end | |
end | |
module PangramAllHash | |
ALPHABET = ('a'..'z') | |
def self.pangram?(phrase) | |
return false if phrase.empty? | |
phrase_hash = phrase_hash(phrase) | |
ALPHABET.all?(&phrase_hash.method(:[])) | |
end | |
def self.phrase_hash(phrase) | |
phrase.chars.reduce({}) do |hash, letter| | |
hash[letter.downcase] ||= true | |
hash | |
end | |
end | |
end | |
phrases = [ | |
'', | |
'abcdefghijklmnopqrstuvwxyz', | |
'the quick brown fox jumps over the lazy dog', | |
'a quick movement of the enemy will jeopardize five gunboats', | |
'five boxing wizards jump quickly at it', | |
'the_quick_brown_fox_jumps_over_the_lazy_dog', | |
'the 1 quick brown fox jumps over the 2 lazy dogs', | |
'7h3 qu1ck brown fox jumps ov3r 7h3 lazy dog', | |
'"Five quacking Zephyrs jolt my wax bed."', | |
'the quick brown fox jumps over with lazy FX', | |
] | |
Benchmark.ips do |x| | |
x.config(:time => 5, :warmup => 2) | |
x.report("PangramArraySubtraction") do | |
phrases.each{ |phrase| PangramArraySubtraction.pangram?(phrase) } | |
end | |
x.report("PangramArrayAllInclude") do | |
phrases.each{ |phrase| PangramArrayAllInclude.pangram?(phrase) } | |
end | |
x.report("PangramAllSquareBrackets") do | |
phrases.each{ |phrase| PangramAllSquareBrackets.pangram?(phrase) } | |
end | |
x.report("PangramAllHash") do | |
phrases.each{ |phrase| PangramAllHash.pangram?(phrase) } | |
end | |
x.compare! | |
end |
Author
marksiemers
commented
Jun 1, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment