Permuted order challenge.

  • Thread starter Thread starter William Stacey [MVP]
  • Start date Start date
W

William Stacey [MVP]

Have an ArrayList in a class with 1 or more elements (no fixed upper bound)
Want a method on the class to return a new ArrayList with the permuted order
of the arraylist so that each call returns different order until it starts
again.
Such that a 3 element arraylist (for example) of elements A,B,C would
return: ABC/BCA/CAB/ACB/BAC/CBA
Any ideas? TIA
 
William Stacey said:
Have an ArrayList in a class with 1 or more elements (no fixed upper bound)
Want a method on the class to return a new ArrayList with the permuted order
of the arraylist so that each call returns different order until it starts
again.
Such that a 3 element arraylist (for example) of elements A,B,C would
return: ABC/BCA/CAB/ACB/BAC/CBA
Any ideas? TIA

Keep an array of integers which show which positions you've got. On
each iteration, start from the end and find the first number you can
increment (however many times is necessary) such that the new number in
that position isn't earlier in sequence. Then reorder the rest of the
numbers (from after that position) to be the unused numbers in order.
(You'll never be able to increment the actual last position, of
course.)

So, for 4 items you'd go:

0123
0132 (inc position 2)
0213 (inc position 1 - can't do 2)
0231 (inc position 2)
0312 (inc position 1)
0321 (inc position 2)
1023 (inc position 0)
1032 (inc position 2)
1203 (inc position 1)

etc

I suspect there's an easier way, but I don't know it offhand. A search
for permutation algorithms may well find it.
 
Hi William,

Does Jon's reply makes sense to you? Do you still have concern on this
issue?

Please feel free to feedback. Thanks

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
Back
Top