5
$\begingroup$

I have a list of integers which I am trying to order in the following way:

  • remove all zeros from the list
  • sort in increasing order of absolute value
  • put positive values before negative values

I.e. the list n={0,1,-3,3,-3,0,12,10,0} should go to {1,3,-3,-3,10,12}.

I'm very new to Mathematica and can't figure this out although it's probably simple.

Things I tried:

  • define a function simplifyList[n_]:=Sort[n, Less] /. {Longest[0 ...], x___} :> {x}. This only works when there are no negative values, otherwise zeros remain.

  • Sort[DeleteCases[n, 0], Abs[#1] < Abs[#2] &]. This returns {1, -3, 3, -3, 10, 12} with the list n above, i.e. the negative/positive numbers with same absolute value are not sorted.

Is there a simple way of doing this? Speed is quite important here, as the simplifying-list function will be used 1000s of times, so the more efficient the better.

$\endgroup$

3 Answers 3

10
$\begingroup$
ClearAll[f]
f = ReverseSortBy[Minus @* Abs] @* DeleteCases[0] 

f @ n

{1, 3, -3, -3, 10, 12}

$\endgroup$
3
$\begingroup$

Try this:

In[21]:= n = (Sort[{0, 1, -3, 3, -3, 0, 12, 10, 0} /. 
x_ /; x == 0 -> Nothing, Abs[#1] < Abs[#2] &])

(* Out[21]= {1, -3, 3, -3, 10, 12} *)

Then

     In[23]:= Sort[n, If[Abs[#1] == Abs[#2], #1 > #2] &]

(*   Out[23]= {1, 3, -3, -3, 10, 12}   *)

Have fun!

$\endgroup$
0
0
$\begingroup$
n = {0, 1, -3, 3, -3, 0, 12, 10, 0};

-SortBy[-n, Abs] // Cases[Except[0]]

or

GroupBy[n, Abs, ReverseSort] // KeySort // KeyDrop[0] // 
  Values // Catenate

{1, 3, -3, -3, 10, 12}

$\endgroup$

Your Answer

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

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