Ruby way to group anagrams in string array

前端 未结 2 594
爱一瞬间的悲伤
爱一瞬间的悲伤 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)

    0 讨论(0)
  • 2020-12-28 11:10

    Like that:

     a = ['cars', 'for', 'potatoes', 'racs', 'four','scar', 'creams', 'scream']
     a.group_by { |element| element.downcase.chars.sort }.values
    

    Output is:

    [["cars", "racs", "scar"], ["for"], ["potatoes"], ["four"], ["creams", "scream"]]
    

    If you want to you can turn this one-liner to a method of course.

    0 讨论(0)
提交回复
热议问题