In ruby ,
1.upto(10).to_a.group_by{|x| x%3}
gives
{1=>[1, 4, 7, 10], 2=>[2, 5, 8], 0=>[3, 6, 9]}
I would like use patten replace as a hash table in Mathematica. For example:
{1 -> {1, 4, 7, 10}, 2 -> {2, 5, 8}, 0 -> {3, 6, 9}}
I know I can use GatherBy
, but it only contains the value. I tried to solve and I feel it isn't efficient for a large list.
fun = Mod[#, 3] &;
Thread[fun /@ #[[All, 1]] -> #] &@GatherBy[Range[10], fun]
GatherBy
... I would probably write the second line asWith[{fun = Mod[#, 3] &}, MapIndexed[fun@First@#2 -> # &, GatherBy[Range@10, fun]]]
On my machine, it does 10^7 integers in under a second. $\endgroup$ – rm -rf♦ Nov 26 '12 at 15:16