5
$\begingroup$

Consider the following list

list={{{0,0,0},0},{{0,0,1},a},{{0,0,-1},-a},{{1,0,1},b},{{1,0,0},-b},{{1,1,1},a+b},{{1,1,1},a-b},{{-1,0,-1},{-a-b}},{{-1,0,-1},{-a+b}}};

how can this list be sorted such that a>b>0, therefore the expected result would be

list={{{1,1,1},a+b},{{0,0,1},a},{{1,0,1},b},{{1,1,1},a-b},{{0,0,0},0},{{-1,0,-1},{-a+b}},{{1,0,0},-b},{{0,0,-1},-a},{{-1,0,-1},{-a-b}}};

in this specific example we also have that 2b>a however it is not that important.

$\endgroup$
4
$\begingroup$

After fixing your list (the last two items had a list wrapped around the second element), the following works:

list = {{{0, 0, 0}, 0}, {{0, 0, 1}, a}, {{0, 0, -1}, -a}, {{1, 0, 1}, b}, {{1, 0, 0}, -b}, {{1, 1, 1}, a + b}, {{1, 1, 1}, a - b}, {{-1, 0, -1}, -a - b}, {{-1, 0, -1}, -a + b}};

Sort[list, FullSimplify[#[[2]] > #2[[2]], a > b > 0 && 2 b > a] &]
(* {{{1, 1, 1}, a + b}, {{0, 0, 1}, a}, {{1, 0, 1}, b}, {{1, 1, 1}, a - b}, {{0, 0, 0}, 0}, {{-1, 0, -1}, -a + b}, {{1, 0, 0}, -b}, {{0, 0, -1}, -a}, {{-1, 0, -1}, -a - b}} *)

This works by supplying a custom comparison function to Sort that simplifies "left">"right" given the assumptions on a and b.

$\endgroup$
3
$\begingroup$
ordering = Reverse @ 
   Ordering[list[[All, 2]] /. FindInstance[a > b > 0 && 2 b > a, {a, b}][[1]]];

list[[ordering]]
{{{1, 1, 1}, a + b}, {{0, 0, 1}, a}, {{1, 0, 1}, b}, {{1, 1, 1}, a - b}, 
 {{0, 0, 0}, 0}, {{-1, 0, -1}, -a + b}, {{1, 0, 0}, -b}, {{0, 0, -1}, -a}, 
 {{-1, 0, -1}, -a - b}}

This should be faster for long lists.

$\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.