3
$\begingroup$
A={1, 2, 3, 4, 5}
Permutations[A, {3}]

I need to print all permutations where the first number is bigger than the second and the second number is bigger than the third:

lets say (5,4,3), ...(5,3,1), ...(4,2,1)...(3,2,1). it needs to be done with A={1, 2, 3, 4, 5}

$\endgroup$
0
4
$\begingroup$
Select[Permutations[A, {3}], Greater @@ # &]
$\endgroup$
1
  • $\begingroup$ just perfect! thanks a lot :D $\endgroup$ – Jovan Angelov May 19 '15 at 15:06
11
$\begingroup$
Subsets[Reverse@Range[5], {3}]

{{5, 4, 3}, {5, 4, 2}, {5, 4, 1}, {5, 3, 2}, {5, 3, 1}, {5, 2, 1}, {4, 3, 2}, {4, 3, 1}, {4, 2, 1}, {3, 2, 1}}

Reverse /@ Subsets[Range[5], {3}]

{{3, 2, 1}, {4, 2, 1}, {5, 2, 1}, {4, 3, 1}, {5, 3, 1}, {5, 4, 1}, {4, 3, 2}, {5, 3, 2}, {5, 4, 2}, {5, 4, 3}}

$\endgroup$
2
  • $\begingroup$ I took a quick look at execution times for the three proposed solutions, just for fun. Mine below and @Algohi's are roughly equivalent, but yours blows us both clean out of the water! It makes sense considering that you are doing no pattern matching etc, but it's still pretty impressive! Thanks for posting this! (+1) $\endgroup$ – MarcoB May 19 '15 at 15:19
  • $\begingroup$ @MarcoB, thank you for the upvote. There are a whole lot more Permutations than Subsets (which leads to about 10x increase in Timing for Range[200] even without the selection part). Then, you need to process this huge set to find the right elements -- which, in turn, takes ~10x the time it takes to construct the Permutations. $\endgroup$ – kglr May 19 '15 at 22:00
2
$\begingroup$

Expanding a little on the OP's problem, here is an alternative method based on pattern matching:

SeedRandom[1]
set = RandomInteger[100, 5]

Cases[Permutations[set, {3}], {___, x_, ___, y_, ___, z_, ___} /; x > y > z]

Here is the set:

{80, 14, 0, 67, 3}

And here are the desired permutations:

{ {80, 14, 0}, {80, 14, 3}, {80, 67, 14}, {80, 67, 0}, {80, 67, 3}, {80, 3, 0}, {14, 3, 0}, {67, 14, 0}, {67, 14, 3}, {67, 3, 0} }

This method does not require the original list to be sorted, whereas kguler's does as it is currently written (although of course that would be trivially easy to do). Of course, that is not an issue in the specific case proposed by the OP, since the OP's list is in fact already sorted.

Of course, either method produces the same results:

set = Range[5];
Sort@Cases[Permutations[set, {3}], {___, x_, ___, y_, ___, z_, ___} /; x > y > z];
Sort@(Reverse /@ Subsets[set, {3}]);
% == %%

(*Out: True *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.