Commit ca8243f

mo <mokha@cisco.com>
2017-05-19 17:37:30
optimize the match function.
1 parent 11eee67
spec/spec_helper.rb
@@ -14,6 +14,7 @@
 #
 # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
 require 'byebug'
+require 'ruby-prof'
 RSpec.configure do |config|
   # rspec-expectations config goes here. You can use an alternate
   # assertion/expectation library such as wrong or the stdlib/minitest
@@ -98,4 +99,12 @@ RSpec.configure do |config|
   # as the one that triggered the failure.
   Kernel.srand config.seed
 =end
+
+  def with_profiler
+    result = RubyProf.profile do
+      yield
+    end
+    printer = RubyProf::GraphPrinter.new(result)
+    printer.print(STDOUT, {})
+  end
 end
spec/word_ladder_spec.rb
@@ -41,11 +41,18 @@ An integer representing the length of the shortest transformation sequence from
 DOC
 
 describe "word_ladder" do
-  def match?(word, other, length: word.chars.size)
-    #(word.chars & other.chars).count == length - 1
-    transposed = [word.chars, other.chars].transpose
-    matching = transposed.find_all { |(x, y)| x == y }.count
-    matching >= length - 1
+  def match?(word, other)
+    acceptable = 1
+    failures = 0
+    word.size.times do |n|
+      if word[n] != other[n]
+        failures += 1
+        if failures > acceptable
+          return false
+        end
+      end
+    end
+    true
   end
 
   # use a queue to do a breadth (level) first search.
@@ -108,4 +115,9 @@ describe "word_ladder" do
     words = ["peale", "wilts", "place", "fetch", "purer", "pooch", "peace", "poach", "berra", "teach", "rheum", "peach"]
     expect(word_ladder(words, begin_word: "teach", end_word: "place")).to eql(4)
   end
+
+  it do
+    words = ['chai', 'chat', 'coat', 'cost', 'cast', 'case', 'came', 'tame']
+    expect(word_ladder(words, begin_word: "chai", end_word: "tame")).to eql(8)
+  end
 end
Gemfile
@@ -3,3 +3,4 @@ source "https://rubygems.org"
 
 gem 'rspec'
 gem 'byebug'
+gem 'ruby-prof'
Gemfile.lock
@@ -16,6 +16,7 @@ GEM
       diff-lcs (>= 1.2.0, < 2.0)
       rspec-support (~> 3.6.0)
     rspec-support (3.6.0)
+    ruby-prof (0.16.2)
 
 PLATFORMS
   ruby
@@ -23,6 +24,7 @@ PLATFORMS
 DEPENDENCIES
   byebug
   rspec
+  ruby-prof
 
 BUNDLED WITH
    1.14.6