Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby 1.9 bug? -- Array.permutation

Tags:

ruby

While trying problem 41 from the Euler Project, I ran across what seems to be a bug in the Ruby 1.9 implementation of Array.permutation. Here's the problem code isolated:

n = 4
slice = '987654321'.chars.to_a[-n..-1]
puts "slice = #{slice.join}"
slice.permutation(n) {|perm| puts perm.join}

slice2 = slice.dup
puts "slice2 = #{slice2.join}"
slice2.permutation(n) {|perm| puts perm.join}

slice3 = []
(0...n).each {|i| slice3[i] = slice[i]}
puts "slice3 = #{slice3.join}"
slice3.permutation(n) {|perm| puts perm.join}

My output for slice and slice2 is:

slice = 4321
9876
9867
9786
9768
9687
...

However, slice3 comes out right, with the digits 1 to 4 being permuted. Also n = 4 is the first value that has this problem. When I set n = 3, I get the expected output. Is this a bug, or am I mis-coding something? A quick Google search didn't turn up anything.

like image 829
Greg Charles Avatar asked Aug 19 '10 17:08

Greg Charles


1 Answers

It is a known bug which is fixed in 1.9.2p136 and newer.

Easiest way around it, besides updating to a more recent Ruby, is to insure your array is not "shared", either by building a new one (like your slice3), or simply "modifying" it, e.g. slice += [].

like image 141
Marc-André Lafortune Avatar answered Oct 17 '22 20:10

Marc-André Lafortune