私はルビーが初めてで、そのような問題に取り組んでいます:
n 個の番号付きの手紙と n 個の番号付きの封筒があります。文字 x をエンベロープ x に入れることはできません (OP は、インデックス x-1 に x の値がない値のみを必要とします) 私が望むのは、すべての可能なケースを出力することです。
配列のインデックス + 1 ---> エンベロープの番号
配列の要素 ---> 文字の番号
Input: n = 3.
Output: [2, 3, 1], [3, 1, 2]
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]
これが私のコードです:
$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
よりエレガントなソリューションを探しています。