views:

290

answers:

2
+6  A: 

This looks like you want to generate permutations of your list in lexical order. Those search terms should start you on a useful path.

For instance, Python includes this in the itertools module from version 2.6 on. That documentation shows code that implements such an algorithm.

Novelocrat
+6  A: 

This gives you next permutation:

bool Increase(int[] values) {
   // locate the last item which is smaller than the following item
   int pos = values.Length - 2;
   while (pos >= 0 && values[pos] > values[pos + 1]) pos--;
   // if not found we are done
   if (pos == -1) return false;
   // locate the item next higher in value
   int pos2 = values.Length - 1;
   while (values[pos2] < values[pos]) pos2--;
   // put the higher value in that position
   int temp = values[pos];
   values[pos] = values[pos2];
   values[pos2] = temp;
   // reverse the values to the right
   Array.Reverse(values, pos + 1, values.Length - pos - 1);
   return true;
}

Edit:
Changed Array.Sort to Array.Reverse. The items are always in descending order and should be in ascending order, so they give the same result.

Guffa
do you have a Ruby equivalent to that Array.Sort part?
NixNinja
+1 - Nice algorithm. BTW, this is C#, right?
paracycle
( and thank you )
NixNinja
@Stefan: I have never used Ruby, so no. This overload of the Array.Sort method sorts the part of the array starting at the index in the second argument and the length in the third argument.
Guffa
@paracycle: Thanks. Yes, it's C#. I invented it just now, or probably reinvented it... :)
Guffa
Come to think of it, an alternative to sorting the part of the array is to simply reverse it. The items will always be in descending order and should be in ascending order afterwards.
Guffa