I have been reading Erlang systematically recently, and I am currently using "Erlang Programming" as a learning material. After reading the first seven or eight chapters, I tried to write something, but found that I was at a loss, and there were very few helpful materials and documents.
Actually, I hope someone can study or discuss with me.
Today’s topic: Shuffle a List.
Method 1: A more sophisticated out-of-order solution.
[php]
-module(shuffle).
-export([do/1]).
do(L) ->
Len = length(L),
NL = lists:map(fun(X) -> {random:uniform(Len), X} end, L),
NLL = lists:sort(NL),
[ V || {_,V} <- NLL].
Actually, this problem bothers me a lot. Once a variable is assigned a value, it cannot be modified. This feature makes the original idea and idea of writing a program completely different. What I did above is to use random numbers to generate a list like [{Rand1,Elem1},...,{RandN,ElemN}].
Then use sort to sort, and then print out Elem again, thus achieving the out-of-order effect.
The results are as follows:
[php]
45> c(shuffle).
{ok,shuffle}
46> shuffle:do([1,2,3,4,5]).
[4,5,1,2,3]
47> shuffle:do([1,2,3,4,5]).
[2,1,5,3,4]
48> shuffle:do([1,2,3,4,5]).
[3,1,2,4,5]
49> shuffle:do([1,2,3,4,5]).
[1,5,2,3,4]
50> shuffle:do([1,2,3,4,5]).
[5,1,4,3,2]
51>
Method 2: Universal Shuffling Algorithm
Continuing from the above, shuffling a List, I think the original general shuffling algorithm is feasible. Try writing another function. It has been tested and works, but I think there is definitely room for optimization. The style of the code still reveals strong procedural thinking.
% Scheme using shuffling algorithm
[php]
do2(L) ->
do2(L,[]).
do2([],L) ->
L;
do2(L1,L2) ->
%io:format("L1=~w L2=~w~n",[L1,L2]),
Len = length(L1),
if
Len > 1 ->
NL = lists:split(random:uniform(Len-1), L1),
NL2 = lists:flatten([T1],[H1|T2]),
L11 = lists:append(L2,[H2]),
do2(NL2, L11);
true ->
do2([],lists:append(L2,L1))
end.
The result is:
128> c(shuffle).
{ok,shuffle}
129> shuffle:do2(lists:seq(0,9)).
[9,2,5,1,8,0,7,3,6,4]
130> shuffle:do2(lists:seq(0,9)).
[8,3,6,5,7,4,9,0,2,1]
131> shuffle:do2(lists:seq(0,9)).
[5,3,7,8,1,9,0,6,2,4]
132> shuffle:do2(lists:seq(0,9)).
[3,0,5,2,1,6,8,4,9,7]
133>
There are a few points worth thinking about whether these two solutions are real shuffling algorithms. Is each number equally likely to appear in a certain position?
There are other methods, welcome to discuss.
http://www.bkjia.com/PHPjc/477638.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477638.htmlTechArticleI have been reading erlang systematically recently. I am currently using "erlang programming" as the learning material. After reading the first seven or eight chapters, I tried to write something, but found myself at a loss. I couldn’t find any helpful information and documents...