Hot answers tagged

36

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


25

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


22

arr = {29400., 28200., 22300., 20900., 20300., 19800., 17400., 16600., 16300., 16100., 15500., 15300., 15300., 15200., 15100., 14900., 14700., 14700., 14400., 13900.} From here RANK gives duplicate numbers the same rank. However, the presence of duplicate numbers affects the ranks of subsequent numbers. For example, in a list of integers sorted in ...


22

This is a great use for the Association data structure, which makes so many tasks in Mathematica that much more pleasant. First, we can just write out a ranking of grades: ranking = {"A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "E", "W"}; Then we take your grades and count how many of each there are into an association with ...


22

This is not simplification. It is canonicalization. Bringing expressions to canonical form is very useful because then two expressions can be compared for equality by simply checking that they have the same structure. Checking equality is a very common operation during symbolic manipulations. a+b and b+a are structurally different, but mathematically ...


20

A bit simpler: Permute[lst, SparseArray[order]] Example: lst = {"e", "c", "a", "d", "b"}; order = {1 -> 5, 2 -> 3, 3 -> 1, 4 -> 4, 5 -> 2}; Permute[lst, SparseArray[order]] {"a", "b", "c", "d", "e"}


18

I also got angry about those randomly picked and ill-implemented benchmarks by the Julia team. I appreciate their efforts (jit compilers are useful), but the Fibonacci example was straight away ridiculous. Here is a compiled quick sort implementation that employs a stack in order to avoid recursive calls. The problem with recursion in CompiledFunctions is ...


17

So I think the docs are mostly clear, if hard to visualize. Here's my version of such a table: { "Numerics" -> { "Negative Integer" -> -1, "Zero" -> 0, "Positive Integer" -> 1, "Negative Float" -> N@-\[Pi], "Positive Float" -> N@\[Pi], "Symbolic Constant (Pi)" -> \[Pi], "...


17

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", ...


17

How about: Module[{tmp = test}, With[{ord=Ordering[tmp]}, tmp[[ord]] = Reverse @ tmp[[ord]]]; tmp ] {56, 9, 4, 3, -5, -2, -3, 1, 2, 7, 60, 58, 8, -4, 10, 6, 59, 5, 57, -1}


16

You could do this: GatherBy[list, Last][[All, 1]] ~SortBy~ Last (* {{d, 3}, {b, 3.04}, {a, 3.1}} *)


16

According to The Chicago Manual of Style, para. 18.57/18.58, punctation marks are ignored. 18.57 The letter-by-letter system. In the letter-by-letter system, alphabetizing continues up to the first parenthesis or comma; it then starts again after the punctuation point. Word spaces and all other punctuation marks are ignored. Both open and ...


16

No, Ordering[Ordering[list]] not optimal. And yes, there is a faster method: list = RandomReal[{-1, 1}, 1000000]; First@RepeatedTiming[ a[[Ordering[list]]] = a = Range[Length[list]]; ] First@RepeatedTiming[ b = Ordering[Ordering[list]] ] a == b 0.13 0.236 True Edit J.M.'s second suggestion is more concise and at least as fast if not slightly ...


15

Rather than it being "too big" for the pattern matcher, the problem here is because of the use of //. which applies the rule repeatedly till the result no longer changes (i.e. the list is sorted). In other words, the issue is that of the complexity of the algorithm you're using (//. with ___) rather than the programming paradigm that you've chosen (pattern ...


15

Ordering @ Ordering @ data {3,1,2} Also: Statistics`Library`GetDataRankings[data] Nest[Ordering, data, 2] Composition[Ordering, Ordering][data] all give {3,1,2}


15

One way to solve the case provided is to apply a DistanceFunction to FindShortestTour. Here, I apply a stiff penalty to the next point that does not share an X or Y value with the current point. pts = {{1, 0}, {2, 0}, {2, 3}, {3, 3}, {3, 4}, {0, 4}, {0, 3}, {1, 3}, {1, 0}}; (*randomize points*) pts = (#[[RandomSample[Range[Length@#], Length@#]]]) &[...


14

SeedRandom[42]; haystack = RandomReal[1, 6300]; AbsoluteTiming[ f = Nearest[haystack -> Range@Length@haystack]; {f[.3, 1], haystack[[f[.3, 1]]]}] (* -> {0.015625, {{3123}, {0.300033}}} *) Of course in this case most of the time is expended calculating the nearest function. If your points aren't changing from one use to the next, the time for ...


14

You can use ReplaceList with a helper function which has the Orderless attribute: ClearAll[f]; SetAttributes[f, Orderless]; ReplaceList[f[a, b, c], f[a___, b___, c___] :> {{a}, {b}, {c}}] // DeleteCases[#, {}, -1] & // Union // Column The DeleteCases and Union are required because the output from ReplaceList includes the empty list {} as a ...


14

Here's another way you might approach this kind of thing -- instead of assigning values to the variables using =, you can make them into rules. For example, here is a collection of "variable names" and values for those variables, and a rule to make the assignment explicit: vars = {a, b, c, d, e}; vals = {5, 4, 3, 2, 1.1}; Thread[Rule[vars, vals]] {a -> ...


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): ...


14

By using assignment to parts. Update: now cleaner. fn[list_, r_] := Module[{n = list}, n[[Values @ r]] = n[[Keys @ r]]; n ] Test: x = {"e", "c", "a", "d", "b"} ; r = {1 -> 5, 2 -> 3, 3 -> 1, 4 -> 4, 5 -> 2}; fn[x, r] {"a", "b", "c", "d", "e"} Performance This outperforms even Shadowray's elegant code: x = RandomReal[1, ...


13

I do not believe that this behaviour is a bug. The correct usage would be SortBy[#age&] or SortBy[Key@"age"]. The rest of this response will explain these assertions. The crucial point is that the "age" argument in SortBy["age"] is not conferred with any special meaning on account of SortBy being used as a Dataset operator. In the absence of such ...


12

To sort by a specific element use a pure function with the number in question. For your case (the second element) just do: SortBy[a, #[[2]] &] {{7, 1, 4}, {1, 2, 3}, {12, 4, 8}, {3, 5, 6}, {10, 7, 1}} You can also use Sort like this: Sort[a, #1[[2]] < #2[[2]] &]


12

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, {...


12

I've decided to follow through on my suggestion in a comment to Kenny's answer to use Morton ordering (a.k.a. Z-ordering) of the colors in RGB space. Here's a short routine to generate the n-th iterate of a d-dimensional Z-curve: Morton[d_Integer, n_Integer] := Array[FromDigits[BitGet[#1, d Range[n - 1, 0, -1] + #2], 2] &, {2^(n d), d}, {0, ...


11

note see bottom of answer for a required fix for version 10+ see here for an alternate approach A 2D example of what i suggested in my comment: Based on Belisarius example..we get three lines obviously not connected properly: m = SparseArray[{i_, j_} -> Sin[i j 9 /10 y], {3, 3}]; alle = Table[Eigenvalues[m], {y, 0, 1, .1}]; original = Show[ ...


11

You have to use a pure function also for SortBy titanic[Select[#age > 65 &] /* SortBy[#age &]] Since #age will pick out the values of the key "age" in the association.


11

Unless you use := for varList definition. a,b... are lost. Here's more about that, in related Q&A: Generate list of strings from a list of assigned variables. So: a = 5; b = 4; c = 3; d = 2; e = 1; varList := {a, b, c, d, e}; (Defer[varList] /. OwnValues[varList])[[{1}, Ordering[varList]]] {e, d, c, b, a}


11

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"], ...


11

OK, I've had this problem before myself. Here's a solution to a harder problem? Take your code to generate the roots list. Remove["Global`*"];//Quiet ClearAll; blackbox[a_]=(x-Sin[a]-1)*(x-Sin[a-Pi]-1) (-1+x-Sin[a]) (-1+x+Sin[a]) xx=Range[0,2*Pi,0.01]; roots=Table[x/.NSolve[blackbox[b]==0,x],{b,xx}]; Add a complication by just scrambling the results. ...


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