Randomize a series of numbers without ever repeating

A well-known unbiased shuffle algorithm is the Fisher-Yates (aka Knuth) Shuffle.

See How To Correctly Shuffle An Array in JavaScript | by Nitin Patel | Medium for an interesting story about shuffling arrays correctly :wink:

You can see a great visualization of the Fisher-Yates shuffle here.

We can use the same code inside executescript_sandbox to shuffle (randomize) any array:

Shuffle array macro, it randomizes a list of animals:

{
  "Name": "shuffle",
  "CreationDate": "2020-7-8",
  "Commands": [
    {
      "Command": "store",
      "Target": "fast",
      "Value": "!replayspeed"
    },
    {
      "Command": "echo",
      "Target": "Fill array with animals in alphabetic order",
      "Value": ""
    },
    {
      "Command": "executeScript_Sandbox",
      "Target": "return new Array ('ape','cat','deer','dog','frog','horse','lion','seal','whale','zebra')",
      "Value": "names"
    },
    {
      "Command": "executeScript_Sandbox",
      "Target": "return ${names}.length",
      "Value": "len"
    },
    {
      "Command": "echo",
      "Target": "array length = ${len}",
      "Value": ""
    },
    {
      "Command": "forEach",
      "Target": "names",
      "Value": "elem"
    },
    {
      "Command": "echo",
      "Target": "${elem}",
      "Value": "blue"
    },
    {
      "Command": "end",
      "Target": "",
      "Value": ""
    },
    {
      "Command": "comment",
      "Target": "Shuffle array with  Fisher-Yates (aka Knuth) Shuffle",
      "Value": ""
    },
    {
      "Command": "executeScript_Sandbox",
      "Target": "var array = ${names}; var currentIndex = array.length, temporaryValue, randomIndex;   while (0 !== currentIndex) {     randomIndex = Math.floor(Math.random() * currentIndex);     currentIndex -= 1;    temporaryValue = array[currentIndex];     array[currentIndex] = array[randomIndex];     array[randomIndex] = temporaryValue;   }    return array; ",
      "Value": "names2"
    },
    {
      "Command": "forEach",
      "Target": "names2",
      "Value": "elem"
    },
    {
      "Command": "echo",
      "Target": "${elem}",
      "Value": "green"
    },
    {
      "Command": "end",
      "Target": "",
      "Value": ""
    }
  ]
}
1 Like