2

Method input: ["eat","tea","tan","ate","nat","bat"]

I have grouped each of the anagrams into their own array within an array through this method and then sorted the array by group size:

def group_anagrams(a)
    a.group_by { |stringElement| stringElement.chars.sort }.values.sort_by(&:size)
end

I am struggling to figure out how to alphabetically sort the resulting arrays within the array here because as you can see nat should come before tan in the middle element of the array:

[["bat"], ["tan", "nat"], ["eat", "tea", "ate"]]

Updating with final solution:

def group_anagrams(a)
    a.group_by { |stringElement| stringElement.chars.sort }.values.map(&:sort).sort_by(&:size)
end

1 Answer 1

2

You need to map this array and sort (map(&:sort))

def group_anagrams(ary)
  ary.group_by { |s| s.chars.sort }.values.map(&:sort)
end
ary = ["eat", "tea", "tan", "ate", "nat", "bat"]
group_anagrams(ary)
# => [["ate", "eat", "tea"], ["nat", "tan"], ["bat"]]
Sign up to request clarification or add additional context in comments.

1 Comment

Please note that this works equally well whether it's ary.group_by { |se| se.chars.sort }.values.map(&:sort).sort_by(&:size) or ary.group_by { |se| se.chars.sort }.values.sort_by(&:size).map(&:sort) (shortened name for brevity's sake)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.