1

Say I have a JavaScript array:

var my_arr = [1,2,3,4,5,6];

There are lots of way to shuffle it, say I already got a function shuffle, like this:

shuffle(my_arr);
// The array might be like [1,5,4,3,2,6];

But when I run it again, the order just changed. I'd like to know whether the shuffle can be fixed to a given value (a number, or a string, or even anything). I need the result to be the same every time if the key is the same key. For example:

var my_arr = [1,2,3,4,5,6];
function shuffle_by_key(arr, key){....}
var new_arr1 = shuffle_by_key(my_arr, 1); 
var new_arr2 = shuffle_by_key(my_arr, 2);
var new_arr3 = shuffle_by_key(my_arr, 1);

The new_arr1 should be the same as new_arr3, because they are generated by the same key "1".

AGamePlayer
  • 7,404
  • 19
  • 62
  • 119
  • @Thilo chance is cool but I it's too heavy, just wondering why it even includes some country/people names in the packed source file. http://chancejs.com/chance.min.js – AGamePlayer Feb 05 '16 at 04:06
  • 1
    Well, all you need is a seedable random number generator and a shuffle method that makes use of that. http://stackoverflow.com/questions/424292/seedable-javascript-random-number-generator – Thilo Feb 05 '16 at 04:13
  • Thanks, great information for me to carry on. – AGamePlayer Feb 05 '16 at 04:54

1 Answers1

0
  1. Implement a hash (md5 or other) function in Javascript
  2. Hash your input "salt", since the hash should always be the same for a given input AND produce pseudo-random numbers
  3. Use output of hash to determine the shuffling, perhaps by using every X digits to iterate over the remaining indices and remove them to the output array
  4. Re-hash as necessary if you run out of hash digits
Nate
  • 1,268
  • 13
  • 20
  • can you give code snippet example of how to do the 4 steps you describe? – mesqueeb Jul 23 '21 at 05:00
  • @mesqueeb Sorry, just saw this. I can't at the moment, but this should get you started. Step 1, implement a hash function. This link should help: https://stackoverflow.com/a/7616484/4946681. Step 2, you need a string to hash, so make sure your input salt is a string, then call your hash on it to get an integer (the linked function also returns negative ints). Step 3, given this int, you need to choose the first index of the array, so modular divide. Say the hash is 49 and the array is length 6, 49%6 is 1, so new 0th element was the old 1st element. Step 4, either use 49%6 or 49%5 for next elem – Nate Jul 29 '21 at 20:28