Reputation: 1
random rd = new random();
int name = rd.Next(0,9);
if(name == 1 )
something will happen
if(name == 2 )
something will happen
if(name == 3 )
something will happen
if(name == 4 )
something will happen
if(name == 5 )
something will happen
.
.
.
How do I make it so it doesn't repeat?
Upvotes: 0
Views: 753
Reputation: 7505
As suggested in some comments, you should create a list (or a stack/queue, depending on your exact implementation) that is sorted "randomly". So, for example, you could do something like this:
class Program
{
static void Main(string[] args)
{
List<int> allElements = new List<int>();
for (int i = 0; i <= 9; i++)
allElements.Add(i);
Random rnd = new Random();
Queue<int> myQueue = new Queue<int>(allElements.OrderBy(e => rnd.NextDouble()));
while (myQueue.Count > 0)
{
int currentInt = myQueue.Dequeue();
Console.WriteLine(currentInt);
}
Console.ReadLine();
}
}
Upvotes: 0
Reputation: 186668
If I understood you right, you want to call all the actions in random order; to do that, create actions, say, an array:
Action[] actions = new Action[] {
() => {Console.Write("I'm the first");},
() => {Console.Write("I'm the second");},
...
() => {Console.Write("I'm the tenth");},
};
then shuffle the collection (array):
// simpelst, not thread safe
static Random generator = new Random();
...
int low = actions.GetLowerBound(0);
int high = actions.GetUpperBound(0);
for (int i = low; i < high; ++i) {
int index = i + generator.Next(high - i + 1);
var h = actions.GetValue(i);
actions.SetValue(actions.GetValue(index), i);
actions.SetValue(h, index);
}
finally, call:
foreach (var action in actions)
action();
Upvotes: 1