Tag Info

New answers tagged

2

Mathematica provides the sorting function Sort and SortBy. Sort has a second argument that allows us to pass a function that compares two elements. SortBy has a second argument that lets us calculate a value (or calculate a list of values) to sort by, but does not let us provide the comparison function. There does not appear to be a straightforward way ...


0

ClearAll[shapeLikeF1, shapeLikeF2]; shapeLikeF1 = With[{l1 = #, l2 = #2, tstF = #3}, Extract[l1, List /@ GatherBy[Range@Length@l2, tstF@l2[[#]] &]]] &; shapeLikeF2 = With[{l1 = #, l2 = #2, tstF = #3}, l1[[#]] & /@ GatherBy[Range@Length@l2, tstF@l2[[#]] &]] &; Examples: list1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; list2 = ...


1

list1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; idx = GatherBy[list1, Mod[#, 3] &] list2 = {"It", "is", "only", "the", "morning", "the", "man", "complained", "I", "shall", "consider", "nothing"}; Part[list2, #] & /@ idx


1

list1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; list2 = {"It", "is", "only", "the", "morning", "the", "man", "complained", "I", "shall", "consider", "nothing"}; GatherBy[Transpose[{list1, list2}], Mod[#[[1]], 3] &][[All, All, 2]] (* {{"It", "the", "man", "shall"}, {"is", "morning", "complained", "consider"}, {"only", "the", "I", ...


5

Ordering[Ordering[data]] (* {3,1,2} *)


1

Here are a couple of possibilities. inOrder1[a_List, a_] := 0 inOrder1[a_List, b_List] /; MatrixQ[{a, b}, IntegerQ] := Sign[First[a - b /. 0 -> Sequence[]]] In[8]:= inOrder1[{1, 2, 1}, {1, 4, 0}] (* Out[8]= -1 *) inOrder2[a_List, b_List] /; MatrixQ[{a, b}, IntegerQ] := Catch[ Module[{sg}, Scan[If[(sg = Sign[#[[1]] - #[[2]]]) != 0, Throw[sg]] ...


0

Never mind, I see the answer. I didn't realize that Sort on lists uses exactly [the inverse of] the sorting I want. So !OrderedQ[a,b]returns True exactly when a>b.


0

I don't know if this is clearer, but as Sort using "lexical" ordering on same-length List comparison, I would transfer the original Lists into same length ones, then invoke Sort on them: Clear[lexicallySort] lexicallySort[lst : {{_?NumericQ ..} ..}] := lst // Sort@PadRight[#,{Length@#,Max[Length/@#]},Min[#]-1]/.Evaluate[Min[#]-1]:>Sequence[] ...



Top 50 recent answers are included