0

the function rnd_act_select() is randomizing four functions further in the code, it is called by a button in Photoshop I have set and everything is working well, but I don't know how to set the randomization with no repeat of the cases until all are executed. Could someone give me a solution to this problem? Thank you.

function rnd_act_select() {
    // random selection
    NumberOfFunctions = 4;//Number of functions in your switch statement.
    var ran = Math.floor(Math.random() * NumberOfFunctions);

    switch(ran) {
        case 0: func_one(); break;
        case 1: func_two(); break;
        case 2: func_three(); break;
        case 3: func_four(); break;
        default : return;
    }
};


I have tried this way, but it doesn't work:

function rnd_act_select() {
// random selection begin
function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}
var arr = [func_one,func_two,func_three,func_four];
var shuf = shuffle(arr);

switch(shuf) {
    case 0: func_one(); break;
    case 1: func_two(); break;
    case 2: func_three(); break;
    case 3: func_four(); break;
    default : return;
}
// random selection end
};


Please I need a clear answer if possible. Thanks

Sean Bean
  • 85
  • 10

1 Answers1

1

This should be easy. To do that, you need to remember what functions you used before. Your algorithm should work like this:

  1. Create an array [0, 1, 2, 3]
  2. Shuffle it.
  3. Run your functions according to the shuffled order.
  4. When your shuffled order is empty, repeat from step 1.
Community
  • 1
  • 1
Georg Schölly
  • 124,188
  • 49
  • 220
  • 267