DEV Community

Discussion on: Solution: Find and Replace Pattern

Collapse
 
fuksito profile image
Vitaliy Yanchuk • Edited

Version in ruby.
I decided to use the incoming pattern as a cipher, not sure how does the middleware cipher add up to performance

def find_and_replace_pattern(words, pattern)
    matches_pattern = ->(word) {
      mapping = {}
      word.chars.each.with_index do |letter, index|
        if (matcher = mapping[letter])
          return if pattern[index] != matcher
        else
          matcher = pattern[index]
          return if mapping.invert.key?(matcher)
          mapping[letter] = matcher
        end
      end

      true
    }

    words.select(&matches_pattern)
end

Enter fullscreen mode Exit fullscreen mode