dwyl / learn-elixir

:droplet: Learn the Elixir programming language to build functional, fast, scalable and maintainable web applications!
1.62k stars 109 forks source link

Question regarding Enum.shuffle #138

Closed jasonkim closed 5 years ago

jasonkim commented 5 years ago

Reading through it, I've noticed that this section uses zoo != Animals.randomise(zoo). This seems like it would fail some of the time due to shuffle returning an array with the same order. Or is Enum.shuffle guaranteed to return in a different order?

RobStallion commented 5 years ago

@jasonkim Great spot 👍. You're exactly right. Enum.shuffle does have the possibility to return the list in the same order. It is extremely unlikely but there is a small chance that this could happen.

If you like, try making a pull request with a fix for this. One solution could be to have a condition in the Animals.randomise function which checks to see if the list passed in is equal to the list returned after the Enum.shuffle, if so call Enum.shuffle again and repeat the process until it is not. (This could have an issue if the list is length of one however. Just something to think about)

(Also, I'm sure there is a much better solution than my suggestion 😉)

jasonkim commented 5 years ago

Thanks for the quick response.

I was thinking about this more and was doing some research, and it's actually not straightforward to test for randomness . Looks like a decent approach would be to test for some sort of statistics about number of different results after shuffle over some run (say 100 runs). I think this would get pretty complex and not really sure if it fits into learning Elixir (just more quirk of RNG and testing). Maybe just a side note about RNG is sufficient?

BTW, I didn't go into changing Animals.randomise as I wasn't sure if that was the intention of the method (returning a list with guaranteed different order). It also surfaces RNG quirkinesses and complicates the method. I didn't want it to be a distraction from the core concept.

Anyways, thank you for your answer. I was just curious about if there was any good way to write test around shuffle type of functions.