Reputation: 3
I'm trying to fill each row of a 2 dimensional array with 6 random numbers from an Enumerable.Range list that contains 45 numbers. Each time 6 numbers have been entered into the specific row of the array, they are removed from the list. The problem is that each row of the array uses the same list until there are no numbers left in it. How do I reset the list for each row?
This is what I have so far:
static void InitMatrix(int[,] mat)
{
List<int> numbers = Enumerable.Range(1, 45).ToList();
Random rnd = new Random();
for (int i = 0; i < mat.GetLength(0); i++)
{
if(mat.GetLength(0)< mat.GetLength(1))
for (int j = 0; j < mat.GetLength(1); j++)
{
int index = rnd.Next(0, numbers.Count );
mat[i, j] = numbers[index];
numbers.RemoveAt(index);
}
}
}
Upvotes: 0
Views: 869
Reputation: 3565
You are declaring your list of numbers outside the for loop. This means that it's not restarted after each row.
static void InitMatrix(int[,] mat) {
Random rnd = new Random();
for (int i = 0; i < mat.GetLength(0); i++)
{
if(mat.GetLength(0)< mat.GetLength(1))
{
List<int> numbers = Enumerable.Range(1, 45).ToList();
for (int j = 0; j < mat.GetLength(1); j++)
{
int index = rnd.Next(0, numbers.Count );
mat[i, j] = numbers[index];
numbers.RemoveAt(index);
}
}
}
}
Code is untested, but it should work.
Upvotes: 1
Reputation: 183
Move the list declaration to below the first (row) loop. That way whenever the loop moves to the next row the list is reinitialized / refreshed if you will...
static void InitMatrix(int[,] mat)
{
Random rnd = new Random();
for (int i = 0; i < mat.GetLength(0); i++)
{
List<int> numbers = Enumerable.Range(1, 45).ToList();
if(mat.GetLength(0)< mat.GetLength(1))
{
for (int j = 0; j < mat.GetLength(1); j++)
{
int index = rnd.Next(0, numbers.Count );
mat[i, j] = numbers[index];
numbers.RemoveAt(index);
}
}
}
}
Upvotes: 1