4

I want to order a bunch of number sequences lexicographically. Did this with

lexo[x_, y_] := x == {} || 
    y != {} && (First[x] < First[y] || First[x] == First[y] && lexo[Rest[x], Rest[y]])
Sort[mysequences, lexo]

and it works, but it is presumably not very efficient, because of recursive self-calls.

There is also a version in one of the answers here which might be better. But maybe Mathematica has something built in for that?

I suspect this since there turns out to be something called Lexicographic for which I could not find any documentation. Also, Combinatorica has things like LexicographicSubsets and LexicographicPermutations except that I want something more general, working for any sequences of numbers.

1 Answers1

2
ClearAll[lexSort1, lexSort2]

lexSort1 = SortBy[x \[Function] PadRight[x, Max[Length /@ #]]]@# &;

lexSort2 = Function[x, SortBy[x, PadRight[#, Max[Length /@ x]] &]];

Examples:

lexSort1 @ Subsets[Range@3]
 {{}, {1}, {1, 2}, {1, 2, 3}, {1, 3}, {2}, {2, 3}, {3}}
lexSort2 @ Subsets[Range@3]
 {{}, {1}, {1, 2}, {1, 2, 3}, {1, 3}, {2}, {2, 3}, {3}}
kglr
  • 394,356
  • 18
  • 477
  • 896