How to shuffle a list in elms?

Say I have a list containing numbers from 1 to 5. How do I write a function in Elm called shuffleList so that it takes a list of integers as an argument and returns a randomized version of the list?

eg.

 shuffleList [1,2,3,4,5] {-5,1,2,4,3-} 

In order of hard coding random seed

+5
source share
2 answers

You probably need the shuffle function from elm-community / random-extra. An example of using this parameter on Ellie

If you want to do this manually, but given the original Seed , you can do the following (this uses some functions from the elm-community / list-extra package)

 import List.Extra exposing (getAt, removeAt) import Random exposing (Seed, int, step) shuffleList : Seed -> List a -> List a shuffleList seed list = shuffleListHelper seed list [] shuffleListHelper : Seed -> List a -> List a -> List a shuffleListHelper seed source result = if List.isEmpty source then result else let indexGenerator = int 0 ((List.length source) - 1) ( index, nextSeed ) = step indexGenerator seed valAtIndex = getAt index source sourceWithoutIndex = removeAt index source in case valAtIndex of Just val -> shuffleListHelper nextSeed sourceWithoutIndex (val :: result) Nothing -> Debug.crash "generated an index outside list" 

Example used by Ellie

+7
source

http://package.elm-lang.org/packages/elm-community/elm-random-extra/1.0.2 has Random.Array.shuffle, so just convert to an array, shuffle and convert back

0
source

Source: https://habr.com/ru/post/1264168/


All Articles