loading...

Discussion on: Daily Challenge #217 - SMS w/ an Old Phone

Collapse
windeep profile image
windeep

Ruby solution

KEYS = {
  "1"=>".,?!", 
  "2"=>"abc", 
  "3"=>"def", 
  "4"=>"ghi", 
  "5"=>"jkl", 
  "6"=>"mno", 
  "7"=>"pqrs", 
  "8"=>"tuv", 
  "9"=>"wxyz", 
  "*"=>"'-+=", 
  "0"=>" ",
  "#"=>''
  }

@chars = { }
KEYS.each_key{|key| @chars[key]=key+'-'}
KEYS.each{|key,str| str.each_char.with_index{|char,index| @chars[char]=key*(index+1) }}

def need_temp?(char1,char2)
   return false if (str= @chars[char1]).nil? || char1.between?('0','9') || char1 == '*'
   return true  if str.include?(char2)
   KEYS[str[0]].include?(char2)
end

def send_message(msg)
  former_char = nil
  upcase = false
  msg.each_char.map do |char|
    sharp=''
    temp=''
    if char.between?('A','Z')
       sharp = upcase ? '' : '#'
       upcase = true if upcase == false
       char.downcase!
    elsif char.between?('a','z')
       sharp = upcase ? '#' : ''  
       upcase = false if upcase
    end
    temp=' ' if sharp.empty?  && need_temp?(former_char,char)
    former_char = char
    sharp + temp + @chars[char]
  end
  .join
end