0

I am working on a console app that randomly selects 2 exercises from an array of exercises and uses them later in a tabata workout. I keep running into issues and the 2 selections are always the same.

Please keep your answers pretty simple as I am a beginner.

string[] tbExercises = new string[] { "Pushups", "Pullups", "Situps", "Mountain Climbers", "Burpees", "Goblet Squats", "Kettlebell Swings" };

List<string> randomExercises = new List<string>();

Random rnd1 = new Random();
string ex1 = tbExercises[rnd1.Next(0, 6)];
randomExercises.Add(ex1);
Random rnd2 = new Random();
string ex2 = tbExercises[rnd2.Next(0, 6)];
randomExercises.Add(ex2);

randomExercises.ForEach(Console.WriteLine);
f4tM1k
  • 1
  • 1
  • "[How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)". – Uwe Keim Mar 18 '20 at 16:28
  • 2
    1st problem is that you are creating a new `Random` each time. don't do that; reuse the same one. – Bradley Uffner Mar 18 '20 at 16:29
  • Admittedly, not an exact duplicate but the reason is still the same. Creating two instances of the `Random` class in such close proximity causes them to have the same seed (which is based on the system's clock) - and that's why they give out the exact same pseudo-random sequence of numbers.If you will remove `rnd2` and use the same `Random` instance from `rnd1`, you'll increase your chances of getting a different number from 0% to some positive percentage. However, that percentage is still going to be lower than 100%. – Zohar Peled Mar 18 '20 at 16:34
  • If you truly want to guarantee no repeats, your best option is to [shuffle](https://stackoverflow.com/questions/273313/randomize-a-listt) the array and then simply select the first two strings from it. – Zohar Peled Mar 18 '20 at 16:36
  • I would have duped to [generate random numbers with no repeat in c#](https://stackoverflow.com/q/10675211/215552) – Heretic Monkey Mar 18 '20 at 16:58
  • Thanks all for the above help! – f4tM1k Mar 18 '20 at 17:00
  • @HereticMonkey good option. Added. – Zohar Peled Mar 18 '20 at 18:54

0 Answers0