a.单进程10万次随机3个元素.
[{"192.168.17.102",27017},
{"192.168.17.102",27018},
{"192.168.17.102",27019}]
b.随机10个元素
[1,2,3,4,5,6,7,8,9,10]
c.随机100个元素
lists:seq(1, 100).
1.https://erlangcentral.org/wiki/index.php/RandomShuffle
We associate each element in the list with a random number. The list is then sorted based on the generated number.We repeat this process log(n) times to ensure a fair shuffle.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%% shuffle(List1) -> List2
%% Takes a list and randomly shuffles it. Relies on random:uniform
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
shuffle(List) ->
%% Determine the log n portion then randomize the list.
randomize(round(math:log(length(List)) + 0.5), List).
randomize(1, List) ->
randomize(List);
randomize(T, List) ->
lists:foldl(fun(_E, Acc) ->
randomize(Acc)
end, randomize(List), lists:seq(1, (T - 1))).
randomize(List) ->
D = lists:map(fun(A) ->
{random:uniform(), A}
end, List),
{_, D1} = lists:unzip(lists:keysort(1, D)),
D1.
a.350~370ms b.1600ms c.26800ms
2.
rotate_new(RotatedList, [L]) ->
[L | RotatedList];
rotate_new(RotatedList, List) ->
R = random:uniform(length(List)),
L = lists:nth(R, List),
rotate_new([L | RotatedList], List--[L]).
a.90ms b.410ms c.13550ms
3. http://stackoverflow.com/questions/8817171/shuffling-elements-in-a-list-randomly-re-arrange-list-elements
1> L = lists:seq(1,10).
[1,2,3,4,5,6,7,8,9,10]
Associate a random number R with each element X in L by making a list of tuples {R, X}. Sort this list and unpack the tuples to get a shuffled version of L.
1> [X||{_,X} <- lists:sort([ {random:uniform(), N} || N <- L])].
[1,6,2,10,5,7,9,3,8,4]
2>
a.120ms b.420ms c.5100ms
4. http://stackoverflow.com/questions/8817171/shuffling-elements-in-a-list-randomly-re-arrange-list-elements
list([]) -> [];
list([Elem]) -> [Elem];
list(List) -> list(List, length(List), []).
list([], 0, Result) ->
Result;
list(List, Len, Result) ->
{Elem, Rest} = nth_rest(random:uniform(Len), List),
list(Rest, Len - 1, [Elem|Result]).
nth_rest(N, List) -> nth_rest(N, List, []).
nth_rest(1, [E|List], Prefix) -> {E, Prefix ++ List};
nth_rest(N, [E|List], Prefix) -> nth_rest(N - 1, List, [E|Prefix]).
For example, one could probably do away with the ++
operation in nth_rest/3
. You don't need to seed the random algorithm in every call to random
. Seed it initially when you start your program, like so: random:seed(now())
. If you seed it for every call to uniform/1
your results become skewed (try with [shuffle:list([1,2,3]) || _ <- lists:seq(1, 100)]
).
a.130ms b.410ms c.8500ms
5.
shuffle(L) ->
shuffle(list_to_tuple(L), length(L)).
shuffle(T, 0)->
tuple_to_list(T);
shuffle(T, Len)->
Rand = random:uniform(Len),
A = element(Len, T),
B = element(Rand, T),
T1 = setelement(Len, T, B),
T2 = setelement(Rand, T1, A),
shuffle(T2, Len - 1).
a.130ms b.390ms c.5850