Jump to content

Permutations: Difference between revisions

→‎{{header|Ruby}}: added another method
(→‎{{header|C++}}: the first permutation was not printed in either case. Also, no need to flush output every time.)
(→‎{{header|Ruby}}: added another method)
Line 1,691:
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
</pre>
 
However, this method will produce indistinct permutation if the array has indictinct elements. If you need to find all the permutations of an array of which many element are the same, the method below will be more efficient.
 
<lang ruby>
class Array
def permutation
@copy = self.dup
sort!
yield self
while true
# from: "The Art of Computer Programming" by Donald Knuth
j = size - 2;
j -= 1 while j > 0 && self[j] >= self[j+1]
if self[j] < self[j+1]
l = size - 1
l -= 1 while self[j] >= self[l]
self[j] , self[l] = self[l] , self[j]
self[j+1..-1] = self[j+1..-1].reverse
yield self
else
break
end
end
self[0..-1] = @copy
end
end
</lang>
 
=={{header|Scala}}==
There is a built-in function that works on any sequential collection. It could be used as follows given a List of symbols:
Cookies help us deliver our services. By using our services, you agree to our use of cookies.