Problem 23 Solution

randomSelect : Random.Seed -> Int -> List a -> ( List a, Random.Seed )
randomSelect seed n list =
    let
        ( l, r, s ) =
            randSelect n ( [], list, seed )
    in
        ( l, s )


randSelect : Int -> ( List a, List a, Random.Seed ) -> ( List a, List a, Random.Seed )
randSelect n ( l, r, seed ) =
    if n > 0 then
        let
            ( idx, seed_ ) =
                Random.step (Random.int 1 (List.length r)) seed

            e =
                elementAt r idx

            r_ =
                dropAt r idx
        in
            case e of
                Nothing ->
                    ( l, r, seed )

                Just x ->
                    randSelect (n - 1) ( x :: l, r_, seed_ )
    else
        ( l, r, seed )


elementAt : List a -> Int -> Maybe a
elementAt list n =
    case List.drop (n - 1) list of
        [] ->
            Nothing

        y :: ys ->
            Just y


dropAt : List a -> Int -> List a
dropAt list n =
    case list of
        [] ->
            []

        x :: xs ->
            (List.take (n - 1) list) ++ (List.drop n list)

Back to problem

results matching ""

    No results matching ""