Ruby way to group anagrams in string array

前端 未结 2 595
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-28 10:39

I implemented a function to group anagrams. In a nutshell:

input: [\'cars\', \'for\', \'potatoes\', \'racs\', \'four\',\'scar\', \'creams\', scream\']

output

2条回答
  •  北海茫月
    2020-12-28 11:09

    You could use the partition function instead of select, implemented in Enumerable. It splits the entries within the array according to the decision-function into two arrays.

    def group_anagrams(words)
      array = []
      until words.empty? 
        word = words.first
        delta, words = words.partition { |match| word.downcase.chars.sort.join.eql?(match.downcase.chars.sort.join ) } )
        array += delta
      end
      array
    end
    

    (untested)

提交回复
热议问题