Hot answers tagged

24

If you're looking for a way to sort the colors in such a way as to make them seem the least discontinuous, then one way to think of it is that each color is a point in a space endowed with a distance metric (either the CIELAB 1976 or the CIELAB2000 perceptual metrics), and you are trying to find a shortest tour that visits each point. We can do that with ...


19

In general SortBy can do pretty much anything that Sort does; in some cases, possibly better or faster. You can find many comparisons on this site if you just search for both function names. I also disagree with @user21382 that his task could not be expressed elegantly in SortBy form: not only can it be done, I would actually argue that it could be done ...


14

SortBy[l, {First@#, -ToCharacterCode@Last@#} &] (*{{1, "u"}, {1, "d"}, {2, "u"}, {2, "d"}, {3, "u"}, {3, "d"}, {4, "u"}, {4, "d"}, {5, "u"}, {5, "d"}, {6, "u"}, {6, "d"}}*) Or the same, but slightly shorter code SortBy[l, {#, -ToCharacterCode@#2} &@@#&] Edit The following uses the same sorting strategy but is much faster (by using this): ...


10

This is due to Sort on lists sorting by the size of the sub-list first, and only applying lexicographic sort for equal-size lists. This is in fact documented. Based on this observation, here is one possibility: ClearAll[lexicographicListSort] lexicographicListSort[lst_List] := Module[{lengths = Length /@ lst, ord}, ord = Ordering @ PadRight[lst, ...


9

I commented on this a bit here: What are the most common pitfalls awaiting new users? Since SortBy was introduced in Mathematica 6 it is preferred where applicable over Sort with a custom comparator. This is because SortBy uses vector application of its second argument over the sort expression then the fast internal sort/ordering function, whereas Sort ...


9

You say I've defined ordering function...which always return True or False. But I don't think that's enough for it to be an ordering function. Consider this example, which also doesn't give the results you expect, myOrderingFunction[arg1_, arg2_] := EvenQ[Round[Sin[ arg1 arg2]]]; list = RandomReal[20, 100]; OrderedQ[Sort[list, myOrderingFunction], ...


8

This is not a complete answer, but it's too long for a comment. It doesn't completely work, but perhaps it might inspire other answers. The idea is to use graph theory and flows. I shall just look at the 3x3 case. First we construct a graph of 9 source nodes and 9 sink nodes. The source nodes flow costlessly straight into the sink nodes, and the sink ...


8

You basically want to permute the elements of the list among some specified set of permutations, and find the ordering of the list among these permutations that is canonically "first". The set of permutations you're interested in is a subgroup of the permutation group $S_n$, generated by two generators, one of which rotates all elements one position to the ...


8

As suggested in the comments, SortBy should work. For example you could do f[Derivative[_][x_][_]] := x f[x_[_]] := x f[x_] := x SortBy[{a, x[t], y[t], x'[t], y'[t], x''[t], y''[t]}, f] One should check how robust this solution is though. Edit And a more compact way of writing f is f[Derivative[_][x_][_] | x_[_] | x_] := x


8

There were comments about the lack of an OrderingBy function, and for this I'll quote Szabolcs I think that OrderingBy is not necessary. It it were to be analogous to SortBy then OrderingBy[list, f] would give exactly the same output as Ordering[f /@ list], which can even be changed to So we can just write orderingBy[list_, f_] := Ordering[f /@ ...


7

Just for fun, how does a 3D Hilbert curve sample the 3D colourspace of RGB? and can it be used to sort colours? HilbertCurve3D[n] generates a 3D Hilbert curve of order n. The code is by Michael Trott from page 93 of The Mathematica Guidebook for Programming. HilbertCurve3D[n_Integer?Positive] := Module[{axiom = "X", recursion = "X" -> {"t", "c", "X", ...


7

Using your code, let me make it clear by introducing an auxiliary function that sums the exponents in an expression sortFunc[expr_] := Total[Exponent[expr, x, List]] Now you can go with Sort[mylist, sortFunc[#1] < sortFunc[#2] &]


7

Look at the Possible Issues section of the documentation for Sort: "Numeric expressions are sorted by structure as well as numerical value" list = {1/2 (1 + Sqrt[5]), 1, 1, 1/2 (1 - Sqrt[5]), 0}; The approach recommended there to Sort by numerical value only is sorted = Sort[list, Less] (* {(1/2)*(1 - Sqrt[5]), 0, 1, 1, (1/2)*(1 + Sqrt[5])} *) ...


7

This gives 5 symbols with the highest rank in "All": In[1]:= EntityValue["WolframLanguageSymbol", "Ranks", "EntityAssociation"] // Query[TakeSmallest[5] /* Keys, "All"] Out[1]= {Entity["WolframLanguageSymbol", "List"], Entity["WolframLanguageSymbol", "Rule"], Entity["WolframLanguageSymbol", "Times"], Entity["WolframLanguageSymbol", "Power"], ...


7

A simple approach giving the requested result is SortBy[list, (#[[2]] /. {"u" -> 0, "d" -> 1}) + 100 #[[1]] &] (* {{1, "u"}, {1, "d"}, {2, "u"}, {2, "d"}, {3, "u"}, {3, "d"}, {4, "u"}, {4, "d"}, {5, "u"}, {5, "d"}, {6, "u"}, {6, "d"}} *) In fact, even simpler is SortBy[list, (# /. {"u" -> 0, "d" -> 1}) &] Simpler yet is ...


7

Using Ordering it's possible to do this. Ordering can be seen as a permutation that brings a list to the identity permutation. And applying Ordering again to this permutation we get the inverse permutation that brings a list from identity to the original order. Using these observations: OrderingToTarget[list_, sourceIds_, targetIds_] := list[[Ordering @ ...


6

Not a bug. The docs: "Sort usually orders expressions by putting shorter ones first, and then comparing parts in a depth‐first manner." You want SortBy[list,N], I think. For more complex cases, use Ordering[] to get a list of indexes and use that to reorder the original list: Ordering@N@list list[[%]] Perhaps you should consider the option of handing ...


5

SortBy is usually a more concise form of Sort, yes, but at times, you may have data that cannot be expressed, or cannot be expressed elegantly, using SortBy. For example, let's suppose that we want to sort the following by age, ascending, then by name, descending: data = { <|"Name"->"Jill", "Age" -> 23|>, <|"Name"->"Jack", "Age" -> ...


4

Let me start by generating a Dataset from your JSON string. Note that I adjusted your expressions a little. jsonRules = "result" /. ImportString[jsonResult, "JSON"]; originalds = Dataset[Association @@@ jsonRules] Rearranging the columns can be accomplished without a helper function. Instead, we pick columns in originalds to generate a new data set with ...


4

Small example on 5x5 matrix: pp = Table[p[i, j], {i, 5}, {j, 5}] One way: pp[[#, #]] &@Insert[Rest@Range[5], 1, -2] Or another: pp[[;; 4, ;; 4]] = RotateLeft[pp[[;; 4, ;; 4]], {1, 1}];


4

No one has mentioned the difference in performance: SeedRandom[0]; data = RandomInteger[{-10000, 10000}, 10^5]; sdata = Sort[data, Abs[#1] < Abs[#2] &]; // AccurateTiming sbdata = SortBy[data, Abs]; // AccurateTiming sbstable = SortBy[data, {Abs}]; // AccurateTiming (* 1.86124 0.0222057 0.00999333 *) As mentioned by MarcoB, the results are ...


4

Horribly inefficient way to do such things. Use IntegerPartitions: set = Range@100; total = 400 s = Select[Tuples[set, 3], Total[#] == t &]; // Timing // First j = Sort[Join @@ Permutations /@ IntegerPartitions[total, {3}, set]]; // Timing // First s == j (* 12.948083 0. True *) The latter is below timing resolution... For your case, ...


4

I don't know what bases you want to sort Unicode words with but why not try sort based on CharacterCode of first Unicode letter: FromCharacterCode[SortBy[ToCharacterCode[{"ɝ", "ʃ", "ɝˈs"}], First]] (*{"ɝ", "ɝˈs", "ʃ"}*) Based on your comment this could be one solution: n = Max[Length /@ ToCharacterCode[{"ɝz", "ɝaz", "ʃ"}]]; FromCharacterCode[ ...


4

I propose using Order, assuming equal-length lists. Order[{1, 3, 5}, {1, 3, 4}] Order[{1, 3, 5}, {1, 5, 2}] Order[{1, 3, 5}, {1, 3, 5}] -1 1 0 You can assign an infix operator if you wish: CirclePlus = Order; {1, 3, 5} ⊕ {1, 3, 4} {1, 3, 5} ⊕ {1, 5, 2} {1, 3, 5} ⊕ {1, 3, 5} -1 1 0 You can convert the numeric output to Boolean as needed, ...


4

This is more of an extended comment to the OP's question and halirutan's answer, although there is the extra solution below that uses SortBy rather than Sort, and I find the syntax of SortBy easier to understand than Sort. In any case, note the following: sortFunc[expr_] := Total[Exponent[expr, x, List]]; order[0] = mylist[[Ordering[Total[Exponent[mylist, ...


4

Your limited example implies that you want to reverse the canonical order for the letters in position 2 so that "u" will appear before "d". I've assumed that all letters of the alphabet could appear in position 2 so if that is the case then this would do it: Flatten[Reverse[GatherBy[Sort[list], First], 2], 1] ...but there is probably a more straight ...


4

NA = Missing["NotAvailable"]; SM = 10^-9.; The situation arises when you make a reverse sort like this one data = {{"Libya", 1, 2, NA, 3}, {"Belgium", NA, 10, 30 , 20}, {"Egypt", NA, NA, 8, 7}, {"USA", 21, 18, 18, 17}}; Reverse @ SortBy[data, #[[2]] &] // TableForm Solution: Temporarily replace missing data with a number small enough to not occur ...


4

This basically directly computes the angle that a line drawn from the origin to the point makes with the horizontal axis, and uses this to sort: list = {{100, 200}, {200, 300}, {300, 300}, {320, 150}, {250, 210}, {350, 220}, {380, 100}, {390, 300}}; ordList = SortBy[list, Apply[N[ArcTan[#1, #2]] &]] (* {{380, 100}, {320, 150}, {350, 220}, {390, 300}, ...


3

listGreater[l1_, l2_] := OrderedQ@{l2, l1}&& l1 =!= l2 listLess[l1_, l2_] := OrderedQ@{l1, l2}&& l1 =!= l2 listGreaterEqual[l1_, l2_] := OrderedQ@{l2, l1} listLessEqual[l1_, l2_] := OrderedQ@{l1, l2} {1, 3, 5}~listGreater~{1, 3, 4} (* True *)


3

If order does not matter you could use IntegerPartition. This yields 15 partitions. ip = IntegerPartitions[15, {3}]; v = Pick[ip, Max@# < 11 & /@ ip] yields: {{10, 4, 1}, {10, 3, 2}, {9, 5, 1}, {9, 4, 2}, {9, 3, 3}, {8, 6, 1}, {8, 5, 2}, {8, 4, 3}, {7, 7, 1}, {7, 6, 2}, {7, 5, 3}, {7, 4, 4}, {6, 6, 3}, {6, 5, 4}, {5, 5, 5}} To count the ...



Only top voted, non community-wiki answers of a minimum length are eligible