tags:

views:

56

answers:

1

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.

+5  A: 

It is a known bug, which is fixed in trunk but is present in the recently released 1.9.2.

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

Marc-André Lafortune
Sweet, thanks! My Japanese is a bit rusty ... no wait, what's that other word? Oh, right, non-existent. However I can see from the code on that link that it's the same issue. I figured I wouldn't be the first one to have noticed it, though I didn't miss by much.Now I'm curious how it's possible that bug occurred. I can't conceive of the internal data structures that would allow slice to seem right, but make the permutation to go wrong, and yet be fine for a slice of three. Is there an English language discussion of it anywhere?
Greg Charles