From: Pablo Bianciotto Date: 2013-04-13T00:39:16+09:00 Subject: Re: Looking for a more elegant solution. --001a11c1b6485eff0f04da2b976d Content-Type: text/plain; charset=ISO-8859-1 Try the following: 1.upto(n).to_a.permutation(n).to_a.delete_if { |perm| perm.any? { |letter| letter == perm[letter -1] } } 2013/4/12 Shaw xx > 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/. > > --001a11c1b6485eff0f04da2b976d Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable
Try the following:

1.upto(n).to_a.permutation(n).to= _a.delete_if { |perm| perm.any? { |letter| letter =3D=3D perm[letter -1] } = }


20= 13/4/12 Shaw xx <lists@ruby-forum.com>
I'm new to ruby and working on such a pr= oblem:

There n numbered letters and n numbered envelops. =A0The 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)]
=A0 =A0 =A0 | =A0 =A0 =A0 =A0 =A0 =A0| =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0|=
=A0envelop1, envelop2, ... , =A0envelop n

The index of Array + 1 ---> the number of the envelop

The element of Array ---> the number of the letter

Input: =A0 =A0 =A0n =3D 3.
Output: =A0 =A0[1, 3, 2], [2, 3, 1]

Input: =A0 =A0 n =3D 4.
Output: =A0 [2, 1, 4, 3], [2, 3, 4, 1], [2, 4, 1, 3], [3, 1, 4, 2],
=A0 =A0 =A0 =A0 =A0 [3, 4, 1, 2], [3, 4, 2, 1], [4, 1, 2, 3], [4, 3, 1, 2],=
=A0 =A0 =A0 =A0 =A0 [4, 3, 2, 1]

Here is my code:
-----------------------
$nums =3D []

def f( already, n, times )
=A0 if n > times
=A0 =A0 $nums << already.dup
=A0 =A0 return
=A0 else
=A0 =A0 1.upto(times) do |i|
=A0 =A0 =A0 next if ((already.include? i) || n =3D=3D i)
=A0 =A0 =A0 already << i
=A0 =A0 =A0 f( already, n+1, times )
=A0 =A0 =A0 already.pop
=A0 =A0 end
=A0 end
end
------------------------

Sorry for my poor English. Thank you very much.

--
Posted via http://= www.ruby-forum.com/.


--001a11c1b6485eff0f04da2b976d--