From: Shaw xx Date: 2013-04-13T00:03:38+09:00 Subject: Looking for a more elegant solution. I'm new to ruby and working on such a problem: There n numbered letters and n numbered envelops. The letter x can't be put into the envelop x. What I want is to print out all the possible cases. [letter(x1), letter(x2), ... , letter(xn)] | | | envelop1, envelop2, ... , envelop n The index of Array + 1 ---> the number of the envelop The element of Array ---> the number of the letter Input: n = 3. Output: [1, 3, 2], [2, 3, 1] Input: n = 4. Output: [2, 1, 4, 3], [2, 3, 4, 1], [2, 4, 1, 3], [3, 1, 4, 2], [3, 4, 1, 2], [3, 4, 2, 1], [4, 1, 2, 3], [4, 3, 1, 2], [4, 3, 2, 1] Here is my code: ----------------------- $nums = [] def f( already, n, times ) if n > times $nums << already.dup return else 1.upto(times) do |i| next if ((already.include? i) || n == i) already << i f( already, n+1, times ) already.pop end end end ------------------------ Sorry for my poor English. Thank you very much. -- Posted via http://www.ruby-forum.com/.