with: Erik Oosterwal
Custom Search
|
1, 2, 3, 4 1, 2, 4, 3 1, 3, 2, 4 1, 3, 4, 2 1, 4, 2, 3 1, 4, 3, 2 2, 1, 3, 4 2, 1, 4, 3 2, 3, 1, 4 2, 3, 4, 1 2, 4, 1, 3 2, 4, 3, 1 3, 1, 2, 4 3, 1, 4, 2 3, 2, 1, 4 3, 2, 4, 1 3, 4, 1, 2 3, 4, 2, 1 4, 1, 2, 3 4, 1, 3, 2 4, 2, 1, 3 4, 2, 3, 1 4, 3, 1, 2 4, 3, 2, 1
If the above list of permutations is sorted correctly, a pattern can be seen.
In the routine a separate array is used to keep track of the repeating pattern.
In the following list of the same permutations the pattern array is shown
next to the pattern. The minimum size of the tracking array is 1 less than
the dimension of the array being manipulated. For our list, we use a tracking
array of 3 elements.
0, 0, 0 1, 2, 3, 4 ^--^ 1, 0, 0 2, 1, 3, 4 ^-----^ 0, 1, 0 3, 1, 2, 4 ^--^ 1, 1, 0 1, 3, 2, 4 ^-----^ 0, 2, 0 2, 3, 1, 4 ^--^ 1, 2, 0 3, 2, 1, 4 ^--------^ 0, 0, 1 4, 1, 2, 3 ^--^ 1, 0, 1 1, 4, 2, 3 ^-----^ 0, 1, 1 2, 4, 1, 3 ^--^ 1, 1, 1 4, 2, 1, 3 ^-----^ 0, 2, 1 1, 2, 4, 3 ^--^ 1, 2, 1 2, 1, 4, 3 ^--------^ 0, 0, 2 3, 4, 1, 2 . . .
It's important to note that during the "swapping" steps that the elements
of the array are not simply being swapped, but the entire subarray is being
mirrored. This can be seen when the third column of the tracking array
changes.
/* Written By Erik Oosterwal */ Dim DataArray(N) Dim TrackingArray(N-1) Set DataArray=[1, 2, 3, 4, 5,... N] Set TrackingArray=[0, 0, 0, ... N-1] Repeat( If TrackingArray(1) < 1 Then( Mirror DataArray(1 - 2) Increment TrackingArray(1) ) Else If TrackingArray(2) < 2 Then( Mirror DataArray(1 - 3) Increment TrackingArray(2) Reset TrackingArray(1) ) Else If TrackingArray(3) < 3 Then( Mirror DataArray(1 - 4) Increment TrackingArray(3) Reset TrackingArray(1, 2) ) Else If TrackingArray(4) < 4 Then( Mirror DataArray(1 - 5) Increment TrackingArray(4) Reset TrackingArray(1, 2, 3) ) Else... . . . Else Stop )
AllPermutations(DataArray(), TrackingArray())( /* Written by Erik Oosterwal */ i=0 While(TrackingArray(i)== i+1)( i++ ) Mirror(DataArray(0), i+2) for(j=0, j<i+1, j++)( TrackingArray(j-1)=0 ) TrackingArray(i)++ return(DataArray(), TrackingArray()) )
Some things to note about this implementation:
1. DataArray and TrackingArray are initialized in the calling routine.
2. The second parameter in the "Mirror" statement is the number elements
to be mirrored.
3. Because of the way the "G" program handles For-Next loops, it required
the indexing of TrackingArray to start at -1. For your implementation of
the routine adjust the indexing to suit your needs.