[erlang-questions] Swap 2 elements within a list a la Erlang ?

Richard Carlsson richardc@REDACTED
Tue Jun 12 09:43:39 CEST 2007


ok wrote:
> Here's another approach:
> 
> 	random_partition(List) ->
> 	    random_partition(List, [], []).
> 
> 	random_partition([], Left, Right) ->
> 	    {Left,Right};
> 	random_partition([X|Xs], Left, Right) ->
> 	    U = random:uniform(),
> 	    if U >= 0.5 ->
> 		random_partition(Xs, Left, [X|Right])
> 	     ; U < 0.5 ->
> 		random_partition(Xs, [X|Left], Right)
> 	    end.
> 
> 	randomise([]) ->
> 	    [];
> 	randomise([X]) ->
> 	    [X];
> 	randomise(Bigger) ->
> 	    {Left, Right} = random_partition(Bigger),
> 	    randomise(Left) ++ randomise(Right).
> 
> This one really wants random bits, not random floats.  It actually
> needs the same number of random bits (ceiling(N.lgN)) as the Fisher-
> Yates method.

I think this should definitely go in the stdlib 'lists' module!

     /Richard




More information about the erlang-questions mailing list