0

I have a list of methods, and I want to select a random method from the list and execute it while a boolean is set to true. I have:

 List<Action> myActions = new List<Action>();

 public void SetupRobot()
 {               
    myActions.Add(mRobot.turnLeft);
    myActions.Add(mRobot.turnRight);
    myActions.Add(mRobot.move);
 }


 private void randomDemo()
    {
        while (mRandomActive)
        {           
                foreach (Action aAction in myActions)
                {
                    //randomly method and execute
                    Random rndm = new Random();
                }
        }
    }

Unsure as to how I would select the method from the list with object rndm

Scott
  • 1,863
  • 2
  • 24
  • 43

2 Answers2

3
private void randomDemo()
{
    Random r = new Random();
    while (mRandomActive)
    {           
        int index = r.Next(myActions.Count);
        var action = myActions[index];
        action();
    }
}
Zbigniew
  • 27,184
  • 6
  • 59
  • 66
  • also to add to the answer: a more [elegant but expensive](http://stackoverflow.com/questions/2019417/access-random-item-in-list#2019433) solution – Manish Mishra May 02 '13 at 08:57
  • Yes, turning `Random` into class variable could be a good idea, especially if you are keep executing `randomDemo()` method. – Zbigniew May 02 '13 at 08:59
1
Random rndm = new Random();    
while (mRandomActive){
    //randomly method and execute
    var index = rndm.Next(myActions.Count);
    myActions[index]();
}
Omar
  • 16,329
  • 10
  • 48
  • 66
Raphaël Althaus
  • 59,727
  • 6
  • 96
  • 122