Tag Info

Hot answers tagged

12

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


9

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}


8

If your operation can be converted to a canonical ranking rather than a pairwise comparison then you can use MaximalBy introduced in version 10. If not a good approach to a single pass through a list is Fold. Here is a function using that: foldMax[list_, p_] := Fold[If[p[##], ##] &, list] This proves to be faster in some cases than using Ordering ...


6

As a followup to the answer by bill s, as of version 10, you should consider using Association instead of lists of rules. In this case, you could do the following: Sort[AssociationThread[{a, b, c, d, e}, {5, 4, 3, 2, 1.1}]] (* <|e -> 1.1, d -> 2, c -> 3, b -> 4, a -> 5|> *) and then Keys@% (* {e, d, c, b, a} *)


3

You could use Hold instead of List in varList: a = 5; b = 4; c = 3; d = 2; e = 1; varList = Hold[a, b, c, d, e]; SortBy[varList, # &] (* Hold[e, d, c, b, a] *)


2

f[x_] := StringTake[IntegerString[Hash[ToString@x, "SHA256"], 16], -4] (* tiny version of requested function *) Clear[collision]; collision::usage = "store potential collisions as downvalues"; collision[_] = {}; Block[ {y}, For[i = 1, i <= 1000, i++, y = f[i]; collision[y] = Append[collision[y], i] ] ]; Sort[Select[#[[1, 1, 1]] -> ...



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