ruby - Array multiplication - what is the best algorithm? -
i have make multiplication of n arrays.
example :
- input = ["a", "b", "c"] * ["1", "2"] * ["&", "(", "$"]
- output = ["a1&", "a1(", "a1$", "a2&", "a2(", "a2$", "b1&", "b1(", "b1$", "b2&", "b2(", "b2$, "c1&, "c1(, "c1$, "c2&", "c2(", "c2$"]
i have created algorithm that, works good.
# input entries = ["$var1$", "$var2$", "$var3$"] data = [["a", "b", "c"], ["1", "2"], ["&", "(", "$"]] num_combinaison = 1 data.each { |item| num_combinaison = num_combinaison * item.length } result = [] in 1..num_combinaison result.push entries.join() end num_repetition = num_combinaison data.each_index |index| item = array.new(data[index]) num_repetition = num_repetition / item.length in 1..num_combinaison result[i-1].gsub!(entries[index], item[0]) if % num_repetition == 0 item.shift item = array.new(data[index]) if item.length == 0 end end end
i'm sure there best way that, don't find it. have tried use product or flatten function without success.
somebody see best solution ?
thanks help.
eric
class array def * other; product(other).map(&:join) end end ["a", "b", "c"] * ["1", "2"] * ["&", "(", "$"] # => # ["a1&", "a1(", "a1$", "a2&", "a2(", "a2$", "b1&", "b1(", "b1$", "b2&", # "b2(", "b2$", "c1&", "c1(", "c1$", "c2&", "c2(", "c2$"]
Comments
Post a Comment