August 23, 2024

P23 - Extract a given number of randomly selected elements from a list.

Example:

> p23:randomSelect(3, [1,2,3,4,5,6,7,8]).
    [3,6,2]

Hint: Use the solution to problem P20

erlang

%Extract a given number of randomly selected elements from a list.

-module(p23).
-export([randomSelect/2]).

randomSelect(0, _) ->
    [];

randomSelect(N, Ls) ->
    Len = length(Ls),
    {Removed, Elem} = p20:removeAt(rand:uniform(Len) -1, Ls),
    [Elem | randomSelect(N - 1, Removed)].
Be first to comment
Leave a reply