Skip to content

Instantly share code, notes, and snippets.

@ka8725
Created January 24, 2012 15:30
Show Gist options
  • Save ka8725/1670700 to your computer and use it in GitHub Desktop.
Save ka8725/1670700 to your computer and use it in GitHub Desktop.
###############################################################################
# SGE New Developer Challenge #2
###############################################################################
Problem:
A colleague of yours has a terrible habit of misspelling their words. The odd
thing is that there is a consistent pattern such that it is always the last
two letters that get messed up.
You've been challenged with the task to clean up the mess. Using a spell
checker will catch most of the mistakes, but not all. We need to find all the
possibilities for the remaining typos and verify that they are syntactically
correct.
Given the provided dictionary text file (wordsEn.txt), return a list
of word pairs whereby swapping the last two letters of the word results in
another valid word. (e.g [coal, cola], [minute, minuet])
Requirements:
- Word length must be greater than 2 characters
- In the case where swapping the last two letters results in the same word, the
word should be omitted (e.g. [bee, bee])
- Your method should output an array of "pairs", where each pair is a 2 element
array (e.g. [[coal, cola], [minute, minuet]])
Your solution will be benchmarked.
Example:
If word list is:
apple
bee
coal
coke
cola
dog
waist
waits
zebra
Your output should be:
[["coal", "cola"], ["waist", "waits"]]
* The order of the pairs and elements w/in those pairs is not important (doesn't have to be alphabetical)
Please check the provided unit tests for example usage and make sure to use
them for verifying your solution!
@ka8725
Copy link
Author

ka8725 commented Jan 24, 2012

class DictionarySearch
  def initialize(file_path)
    @tmp = {}
    File.new(file_path).each_line do |line|
      line.chomp!
      if line.length > 2 && line[-1] != line[-2]
        k = line[0..-3]
        @tmp[k] ||= []
        @tmp[k] << line[-2..-1]
      end
    end
  end

  def word_pairs
    @res if @res
    @res = []
    @tmp.each_pair do |k, v|
      v.each_with_index do |el1, i|
        v[i.next..-1].each_with_index do |el2, j|
          if el1[0] == el2[1] && el1[1] == el2[0]
            @res << ["#{k}#{el1}", "#{k}#{el2}"]
          end
        end
      end
    end
    @res
  end
end

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