How to group anagrams in a string into an array

来源:互联网 发布:淘宝自动确认订单信息 编辑:程序博客网 时间:2024/04/30 09:24
I want to group anagrams in ruby from a given string and the result should be an array containing arrays of anagram groups like
Given String: "scream cars for four scar creams"
here cars and scar are anagrams(made by same characters)

and the result should be [[cars, scar], ['for'], ['four'], ['creams', 'scream']]


"scream cars for four scar creams".split.group_by{|w| w.chars.sort}.values#=> [["scream", "creams"], ["cars", "scar"], ["for"], ["four"]]

0 0
原创粉丝点击