0

so i've been working on a project, and i made this method to take up to 16 values in an array and randomize them into a list. i thought this should have worked but it didnt, whenever it runs it crashes the program but it compiles just fine.

array has "numOfTeams" amount of indexes

private List<string> randomizer()
    {
        List<string> myList = new List<string>();
        Random rand = new Random();
        int randomVar;
        while (myList.Count < numOfTeams)
        {
            randomVar = rand.Next(0, numOfTeams + 1);
            if (array[randomVar] != "null")
            {
                myList.Add(array[randomVar]);
                array[randomVar] = "null";
            }
        }
        return myList;
    }
user1801067
  • 133
  • 2
  • 12
  • 3
    Just to make sure; you do know that the string "null" is not the same as the null pointer? – Lorentz Vedeler Mar 22 '14 at 23:45
  • possible duplicate of [Randomize a List in C#](http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp) – Alexei Levenkov Mar 23 '14 at 01:10
  • If you want code that shuffles an array - look at the duplicate http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp/1262619#1262619 instead of writing your own. If you need help debugging your code - please provide detailed information on exception/error AND what you don't understand about it. – Alexei Levenkov Mar 23 '14 at 01:10

2 Answers2

2
randomVar = rand.Next(0, numOfTeams);
Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68
  • rand.Next(x, y); in this statement the x is inclusive but the y is exclusive. if there are 15 teams and you subtract 1, then the 15th and 14th team will never get selected and the while loop will last forever – user1801067 Mar 22 '14 at 23:46
  • why did you use `-1` ? you could just use `numOfTeams`.max value is exclusive – Selman Genç Mar 22 '14 at 23:46
  • think i found my issue. arrays start at 0, so if numOfTeams = 16 that means 16 is exclusive – user1801067 Mar 22 '14 at 23:49
0

I implemented a method for shuffeling a IList, based on the algorythm of D. E. Knuth (Knuth shuffle or Fisher–Yates shuffle).

Maybe this gives you some hints:

public static void Shuffle<T>(IList<T> list)
{
    Random rand = new Random();
    int index;
    T tmp;
    for (int i = 1; i < list.Count; ++i)
    {
        index = rand.Next(i + 1);
        tmp = list[i];
        list[i] = list[index];
        list[index] = tmp;
    }
}
devmb
  • 805
  • 6
  • 18