Skip to content

Instantly share code, notes, and snippets.

@mk
Created January 19, 2010 11:05
Show Gist options
  • Save mk/280859 to your computer and use it in GitHub Desktop.
Save mk/280859 to your computer and use it in GitHub Desktop.
shuffle(Cards) when is_list(Cards) ->
Size = length(Cards),
lists:foldr(fun(I, Arr) ->
swap(Arr, I, next_int(1, I + 1))
end, Cards, lists:seq(1, Size)).
swap(List, I, J) ->
Ielement = lists:nth(I, List),
Jelement = lists:nth(J, List),
lists:map(fun(Index) ->
if Index == I -> Jelement;
Index == J -> Ielement;
true -> lists:nth(Index, List)
end
end, lists:seq(1,length(List))).
next_int(Lo, Hi) ->
try
crypto:rand_uniform(Lo, Hi)
catch error:badarg ->
crypto:start(),
crypto:rand_uniform(Lo, Hi)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment