6
$\begingroup$

I would like to write the function NewSort function that sorts a list of sorted sublists, basing first on the canonical ordering of subsequent sublist elements. In case of the tie, the shorter sublist should be first.

Example 1:

NewSort[{{1,2,4},{3,4},{1,3}}]

Should give

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

Example 2:

NewSort[{{1,2,3},{1,2},{1}}]

Should give

{{1},{1,2},{1,2,3}}
$\endgroup$
0

1 Answer 1

6
$\begingroup$

Edited version: this is a clean-up by taking into consideration the added example provided in the comments section by the author of the OP.

I am suggesting the following function:

foo[l_List] := 
 Internal`DeleteTrailingZeros /@ 
    PadRight /@ 
     SortBy[#, Table[#[[xx]], {xx, 1, Min[Dimensions /@ l]}] &] &@
  PadRight@l

Now, we define the four lists; two from the OP, the one I had provided as example 3 and the one in the comments by the author of the OP.

list1 = {{1, 2, 4}, {3, 4}, {1, 3}};
list2 = {{1, 2, 3}, {1, 2}, {1}};
list3 = {{1, 2, 4}, {3, 4}, {4, 5}, {1, 3, 7, 8}, {1, 3}};
list4 = {{1}, {1, 2, 4}, {1, 2, 3, 5}};

We act with the function

foo[list1]
foo[list2]
foo[list3]
foo[list4]

fooall

Edit: thanks to the comment by @E. Chan-López, there's the shorter version:

foo[l_List] := 
 DeleteCases[#, 0] & /@ SortBy[#, Min[Length /@ l] &] &@PadRight@l
$\endgroup$
13
  • $\begingroup$ Although this solves the problem, it is a loop-based solution. Is it possible to find something more efficient? $\endgroup$
    – wedelfach
    Feb 21 at 9:54
  • $\begingroup$ @wedelfach by loop, you mean that I used a Table in SortBy? $\endgroup$
    – bmf
    Feb 21 at 9:55
  • $\begingroup$ Yes, if I understood Your solution correctly, it run over every sublist on the parent list. $\endgroup$
    – wedelfach
    Feb 21 at 10:06
  • 2
    $\begingroup$ A bit shorter: DeleteCases[#, 0] & /@ SortBy[#, Min[Length /@ l] &] &@PadRight@l $\endgroup$ Feb 21 at 16:43
  • 1
    $\begingroup$ @E.Chan-López cheers mate. I updated the answer. not sure why I like undocumented stuff so much :-) $\endgroup$
    – bmf
    Feb 22 at 1:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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