and some fun discussing with friends my ideas for some function aimed at shuffling or getting combinations out of an array (but you can easily generalize it to strings or other enumerables).
As the discussion was getting interesting, mostly thanks to the quality of the feed from my acquaintances, I decided to move it in public, so feel free to comment, contribute or, why not, criticize :)
Starting with the shuffle function, first of all I decided I wanted to make it an array class method
(as it is the case in Ruby) and not a mere function
(as it is the case in Python, getting it from the random library) so that I got both a step away from Python's mindset (I really love Python, but I prefer not to be to dependent on a technology and to keep my mind elastic!) and a chance to make some practice with the prototype model of JS.
Then I developed it in a concise and elegant way, only requiring 3 support variables.
I know I may sound clichéd as an Italian focused on frilly elegance, but I discovered that style does matter
: if you can read and think in smooth patterns, then you will do it more often and more efficiently :)
I also know that the CLRS teaches us all that probability-distribution-wise
you should also run j to be chosen in a more restricted range at each step, but as I find it more easy, again elegant and quick to write that way, I kept getting a random j variable from all the values from 0 up to array-length.
Plus, I usually use it on very short (<20 elements) array that get shuffled many times over in my random tests, so the difference is really minimal in the long run :)
Notice the for loop, missing the third element (usually the incrementator/decrementator statement
), as guess what? It is optional!
And so, just initializing the i variable = to the array.length, I got to write the simple and graceful for (i;i;)
I could do that also because I used the pre-put "-
" operator in the instructions to be operated inside the loop): notice that if I were to write "i-
" instead of "-
i", the variable would not have been decremented first, so my method would not have worked (not as expected, at least); another option was to initialize i as array.length-1, but I found the way I choose more neat, not to mention it forced me to remember how the "-
" or "++" operator work according to where you place them :)
Finally, I opted to have a method that worked both in place (as with Ruby) and returning a new array (as in Python) for more comfort of use; you could turn it to work only in place removing the final return statement or to work only returning the array without actually touching the array if you worked on a temporary array instead.
And that's all for the shuffle method and for now; I hope I was of some help and interest to whoever will read this :) #permutation #combination #algorithms