When trying problem 41 from a Euler project, I came across what seems like a bug in implementing Ruby 1.9 in Array.permutation. The problem code is highlighted here:
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 goes right, with numbers 1 through 4 rearranging. Also n = 4 is the first value that has this problem. When I set n = 3, I get the expected result. Is this a mistake, or am I coding something wrong? A quick Google search showed nothing.
source
share