2010-08-05 8 views
7

Sto cercando di trovare tutte le combinazioni di singoli elementi da un numero variabile di matrici. Come posso farlo in Ruby?Ricerca del prodotto di un numero variabile di matrici Ruby

Date due matrici, posso usare Array.product in questo modo:

groups = [] 
groups[0] = ["hello", "goodbye"] 
groups[1] = ["world", "everyone"] 

combinations = groups[0].product(groups[1]) 

puts combinations.inspect 
# [["hello", "world"], ["hello", "everyone"], ["goodbye", "world"], ["goodbye", "everyone"]] 

Come potrebbe questo codice di lavoro quando i gruppi contiene un numero variabile di array?

risposta

13
groups = [ 
    %w[hello goodbye], 
    %w[world everyone], 
    %w[here there] 
] 

combinations = groups.first.product(*groups.drop(1)) 

p combinations 
# [ 
# ["hello", "world", "here"], 
# ["hello", "world", "there"], 
# ["hello", "everyone", "here"], 
# ["hello", "everyone", "there"], 
# ["goodbye", "world", "here"], 
# ["goodbye", "world", "there"], 
# ["goodbye", "everyone", "here"], 
# ["goodbye", "everyone", "there"] 
# ] 
+1

Wow, grazie. Potresti, o qualcuno, spiegare come funziona? –

+2

Una spiegazione di ciò che effettivamente fa sarebbe utile, e probabilmente porterà a una migliore progettazione del codice dell'OP ... – jtbandes

+1

@Ollie: 'Array # product' può prendere più array come argomenti, quindi questo è semplicemente facendo' gruppi [0] .product (groups [1], groups [2], ...) ' – jtbandes

Problemi correlati