DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Benjamin has posted 1 posts at DZone. View Full User Profile

Wrong Word Challege

04.09.2009
| 1093 views |
  • submit to reddit
        Quick script to answer the question: if I accidentally placed my hands a key off of their normal places on the keyboard and typed a word, what are the chances the "wrong word" would be a different valid word.

require 'set'

class String
  def key_shift_up
    key_shift('**********qwertyuioasdfghj')
  end

  def key_shift_down
    key_shift('asdfghjkl*zxcvbnm*********')
  end
  
  def key_shift_right
    key_shift('wertyuiop*sdfghjkl*xcvbnm*')
  end
  
  def key_shift_left
    key_shift('*qwertyuio*asdfghjk*zxcvbn')
  end

  def key_shift(offset_key)
    split(//).collect { |letter| offset_key['qwertyuiopasdfghjklzxcvbnm'.index(letter)].chr }.to_s
  end
end

def print_shifted_word(word, shifted, word_list)
  puts "#{word} > #{shifted}" if word_list.include?(shifted)
end

words = Set.new

File.open("../unixdict.txt") do |file|
  file.each do |line|
    line.chomp!

    words << line if line =~ /^[a-z]{3,}$/
  end
end

words.each do |word|
  print_shifted_word(word, word.key_shift_up, words)
  print_shifted_word(word, word.key_shift_down, words)
  print_shifted_word(word, word.key_shift_left, words)
  print_shifted_word(word, word.key_shift_right, words)
end

Interestingly, there are quite a few.