From: Raf Coremans Date: 2007-07-23T15:43:25+09:00 Subject: Re: array permutations ------=_Part_165716_14879826.1185173007843 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline 2007/7/23, Alex Ciarlillo : > > The other day I ran into a problem where I needed all the permutations > of a given array. I knew I had covered this in some of my CS classes but > couldn't come up with the algorithm at first. I figured it out on the > drive home from work and decided to rubify it and add it as a method to > the array class. This is what I came up with and was just wondering if > anyone else had a cleaner or more effecient way of accomplishing this. > > class Array > def each_perm > if self.size == 1 > yield self > else > self.each_index do |i| > tmp, e = self.dup, self[i] > tmp.delete_at(i) > tmp.each_perm do |x| > yield e.to_a + x > end > end > end > end > end > > > --AC > -- > Posted via http://www.ruby-forum.com/. > > There's a problem with the "to_a" in "yield e.to_a + x". It gets a lot of "default `to_a' will be obsolete" warnings, and it gives the wrong result for, for instance, [1, 2, 'a'..'z'].each_perm. I'd go with "yield [e] + x" instead. For the rest, looks OK to me. Regards, Raf ------=_Part_165716_14879826.1185173007843--