# Sorting a List Based on a Given Order

Suppose I have the following input:

input={{1, 2, 3}, {-2, 4, 6}, {-1, 3, 6}}


How can I sort it according to this list:

order = {{a, b, c}, {a - b, a + b, a + b + c}, {a - c, a + c, a + b + c}}


The expected output is:

{{1, 2, 3}, {-1, 3, 6}, {-2, 4, 6}}


EDIT:

If you compare the input list and the order list you would see that {a, b, c} is {1, 2, 3}, {a - b, a + b, a + b + c} is {-1, 3, 6}, {a - c, a + c, a + b + c} is {-2, 4, 6}. So I want to sort the input in this order:

{{a, b, c}, {a - b, a + b, a + b + c}, {a - c, a + c, a + b + c}}


or expected output is {{1, 2, 3}, {-1, 3, 6}, {-2, 4, 6}}.

If you shuffle the input in any order for example { {-2, 4, 6}, {-1, 3, 6},{1, 2, 3}} the expected output should be the same as {a, b, c} is still {1, 2, 3}.

If order is not a very large list:

order = {{a, b, c}, {a - b, a + b, a + b + c}, {a - c, a + c, a + b + c}};
input = {{1, 2, 3}, {-2, 4, 6}, {-1, 3, 6}};

order /. Cases[Solve[input == #] & /@ Permutations[order], {{p__}} :> p]
(* {{1, 2, 3}, {-1, 3, 6}, {-2, 4, 6}} *)

• Yeah, this works. Commented Mar 22, 2023 at 19:46

I don't really understand what you mean by "sort according to the given order". You haven't given an ordering, you've given an expected result, and it could be achieved through a variety of orderings. We'd need several examples to understand what you mean. But the simplest thing I see that will achieve your expected result is to sort by the reverse:

SortBy[input, Reverse]


{{1, 2, 3}, {-1, 3, 6}, {-2, 4, 6}}

• All elements in the input belong to the order list order = {{a, b, c}, {a - b, a + b, a + b + c}, {a - c, a + c, a + b + c}}. For example, in the given example, if you assign {a, b, c} to be {1, 2, 3} then you would obtain the two remaning elements in the input but {a - b, a + b, a + b + c}, {a - c, a + c, a + b + c} by substituing values of a=1, b=2, c=3. So the problem is sorting the input list with the order list. In the example {a, b, c}={1, 2, 3} to be the first element but it's not always the first. Commented Mar 22, 2023 at 19:32
• If I change the input to input={{-2, 4, 6}, {-1, 3, 6},{1, 2, 3}}, the expected output should also be the same. The method you gave seem to give the expected output but that is not what I want as it doesn't consider the given order list at all. Commented Mar 22, 2023 at 19:32
• Of course the expected output of a sort will be the same if you just shuffle the input. If my answer isn't correct, you need to provide an example input that it won't sort correctly. And, of course, tell us what the correct output should be. Commented Mar 22, 2023 at 19:35