How do I make a function that will randomly select a function from a list?

by on March 5, 2010

Q: I am trying to make a function with a while loop that does a random function from a list. How do I do that?


3 Responses to “How do I make a function that will randomly select a function from a list?”
  1.  

    Are you using a specific programming language or are you just looking for the idea behind how to do it?

     
  2.  

    i’m using javascript.

     
  3.  

    You can use eval() in the loop with an array to call the function you want but it might be easier for you to start out with

    var randomNumber=Math.floor(Math.random()*5) // will give you 0 to 4

    function myRandomFunction (randomNumber) {

    switch (randomNumber())
    {
    case 0:
    function1();
    break;

    case 1:
    function2();
    break;

    ….
    }

    I know you asked about a while loop but I am not sure what conditions you want to put on the loop (ie go so many times or what you are thinking) so I just did it in a function and you can write a while loop that calls that function.

    It also does not pull from a specific list but if you needed to do that you could just use eval with an array pretty easy. I just don’t like the idea of eval unless I know exactly what you are doing because it could allow someone to run code that you don’t want them to run if you are not careful with it.