Manera rubí de agrupar anagramas en una matriz de cadenas

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

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

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

I would like to know if there is a better way to do this. I really think I used too much repetition statements: until, select, delete_if. Is there any way to combine the select y delete_if statement? That means, can selected items be automatically deleted?

Código:

def group_anagrams(words)
  array = []
  until words.empty? 
    word = words.first
    array.push( words.select { |match| word.downcase.chars.sort.join.eql?(match.downcase.chars.sort.join ) } )
    words.delete_if { |match| word.downcase.chars.sort.join.eql?(match.downcase.chars.sort.join ) }
  end
  array
end

Gracias por adelantado,

preguntado el 10 de marzo de 12 a las 13:03

2 Respuestas

Como eso:

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

La salida es:

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

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

respondido 10 mar '12, 14:03

Rule #1 of Ruby programming: learn the methods of Enumerable. Rule #2: see Rule #1. :-) - Jörg W. Mittag

Its weird that this works on my machine, but not in heroku! My site goes down when I have this on heroku... - alexandrecosta

When I run this, I only get: - n como

Podrías usar el partition function instead of select, implemented in enumerables. 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

(no probado)

respondido 10 mar '12, 14:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.