Ruby way to group anagrams in string array

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

提交回复
热议问题