Skip to content

Instantly share code, notes, and snippets.

@marksiemers
Last active June 1, 2018 18:22
Show Gist options
  • Save marksiemers/7a10adc059f2c1909447c96b12aad2c8 to your computer and use it in GitHub Desktop.
Save marksiemers/7a10adc059f2c1909447c96b12aad2c8 to your computer and use it in GitHub Desktop.
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
@marksiemers
Copy link
Author

Calculating -------------------------------------
PangramArraySubtraction
                          8.826k (± 1.5%) i/s -     44.523k in   5.045625s
PangramArrayAllInclude
                         14.644k (± 1.6%) i/s -     74.205k in   5.068475s
PangramAllSquareBrackets
                         19.093k (± 1.5%) i/s -     96.876k in   5.075205s
      PangramAllHash      4.384k (± 3.3%) i/s -     22.250k in   5.081523s

Comparison:
PangramAllSquareBrackets:    19092.7 i/s
PangramArrayAllInclude:      14644.1 i/s - 1.30x  slower
PangramArraySubtraction:      8826.0 i/s - 2.16x  slower
      PangramAllHash:         4383.7 i/s - 4.36x  slower

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment