Search code examples
randomelm

How to get a random element in a given List in Elm?


I'm building a sliding puzzle game:

enter image description here

From this initial position, I'd like to shuffle the puzzle, say 100 moves.

I'd like the puzzle to be shuffled differently each time.

This probably means that I need to call Random.initialSeed with a different number every time, which means that I need to use something like the current time.

Unfortunately, I couldn't find how to get the current time.

In every given state, I have a list of possible moves. For example, in the initial position above: [MoveRight, MoveDown]

So, basically, my question is: how to get a random element in a given List?

share-elm example would be appreciated.


Solution

  • Rough answer (not near a compiler right now):

    If you want to vary the seed based on the current time, add Time.every to your signal graph:

    http://package.elm-lang.org/packages/elm-lang/core/2.1.0/Time#every

    Keep the last seen timestamp in your model, then, when you need to shuffle, use it to seed your random. Generate an integer in the range [1, length list], and then pick the element of that index.

    Hope that's enough of a hint, please yell if it isn't and I will elaborate when I get chance.