Thursday, July 7, 2011

How to re-implement a cartesian product algorithm

Yes. So did I waste my time, or not? Of course not. I just got a big slap in my programming face. Un pollazo. I over-implemented a cartesian product, without even noticing it. But it's fantastic, I can learn every day :)
I was even showing it around to my friends at work. They didn't notice too! Maybe this algorithm could be used for something else. But I have no fucking clue where :D
Of course I learned a lot, but still, feel a bit stupid. Do not overdo and read more - that is the lesson of today!
def cartprod(*args)
result = [[]]
while [] != args
t, result = result, []
b, *args = args
t.each do |a|
b.each do |n|
result << a + [n]
end
end
end
result
end
# Posted here http://www.ruby-forum.com/topic/95519

Ou programming... my dear...

No comments:

Post a Comment