Created
July 24, 2013 09:31
-
-
Save artefactop/6069203 to your computer and use it in GitHub Desktop.
Get N random elements from a list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env escript | |
main([NS, SL]) -> | |
try | |
N = list_to_integer(NS), | |
List = eval(SL), | |
io:format("Result: ~p~n", [random(List,N)]) | |
catch | |
_:_ -> | |
usage() | |
end; | |
main(Input) -> | |
io:format("Input: ~p~n", [Input]), | |
usage(). | |
usage() -> | |
io:format("usage: random N [ele1,ele2,ele3,ele4]\n"), | |
halt(1). | |
random(L, N) -> | |
random(list_to_tuple(L), N, []). | |
random({},_,Acc) -> | |
Acc; | |
random(_,0,Acc) -> | |
Acc; | |
random(T, N, Acc) -> | |
{A1,A2,A3} = os:timestamp(), | |
random:seed(A1, A2, A3), | |
Rand = random:uniform(size(T)), | |
E = erlang:element(Rand, T), | |
random(delete_element(Rand, T), N-1, Acc ++ [E]). | |
delete_element(N,T) -> %% change for erlang:delete_element | |
L = erlang:tuple_to_list(T), | |
Ele = erlang:element(N, T), | |
erlang:list_to_tuple(lists:filter(fun(X) -> X =/= Ele end, L)). %%BUG when exits duplicate elements | |
eval(S) -> | |
Last = lists:last(S), | |
if | |
Last =/= 46 -> | |
eval(S ++ ".",[]); | |
true -> | |
eval(S,[]) | |
end. | |
eval(S,Environ) -> | |
{ok,Scanned,_} = erl_scan:string(S), | |
{ok,Parsed} = erl_parse:parse_exprs(Scanned), | |
{value, R, _} = erl_eval:exprs(Parsed,Environ), | |
R. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment