Rotating letters in a string so that each letter is shifted to another letter by n places

前端 未结 4 1581
無奈伤痛
無奈伤痛 2021-01-05 20:07

I have been tasked with coming up with a way of encoding a string. Among other things, I need to shift each letter by a given number but the transformed letter must be a let

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-05 20:43

    Your mistake is that you just blindly shift characters and don't use your letters array to wrap around.

    def play_pass(str, n)
      letters = ('a'..'z').to_a
    
      str.chars.map do |x| 
        if letters.include?(x.downcase)
          idx = letters.index(x)
          new_idx = (idx + n) % letters.length
          letters[new_idx]
        else
          x
        end
      end.join
    
    end
    
    play_pass('ay1', 2) # => "ca1"
    

    The key to success here is the modulo operator (%). We use to get an index of a substitution character from letters array. It guarantees that the index will always be within bounds of the array. Instead of going past the end, it wraps around.

    Read up on it. It's useful in many places.

提交回复
热议问题