英文:
c# - trying to randomize a 2d array
问题
我正在尝试创建一个二维数组,其中每一行的元素都是打乱顺序的。例如,在一个3x5的数组中,每一行都将包含1、2和3,但元素的顺序将不同:
我想要的结果:
1 3 2
2 1 3
2 3 1
3 1 2
1 2 3
我尝试过的代码:
//初始化一个矩阵
int[,] matrix = new int[3, 5];
Random rnd = new Random();
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
matrix[i,j] = rnd.Next(1,3);
Console.WriteLine(matrix[i,j]);
}
Console.ReadLine();
}
这似乎很简单,但作为一个新手,我为这个问题苦苦挣扎了好几天。
任何帮助或指引将不胜感激!
英文:
I am trying to make a 2d array that has shuffled elements in each row. For example, in a 3x5 array, each row will have 1, 2, and 3, but the order of the elements will be different:
what I want:
1 3 2
2 1 3
2 3 1
3 1 2
1 2 3
code I've tried:
//initialize a matrix
int[,] matrix = new int[3, 5];
Random rnd = new Random();
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
matrix[i,j] = rnd.Next(1,3);
Console.WriteLine(matrix[i,j]);
}
Console.ReadLine();
}
It seems fairly easy, but as a newbie, I've been struggling for days over this problem.
Any help or lead will be appreciated!
答案1
得分: 1
你可以创建一个包含1、2和3的列表,然后为每行对其进行洗牌。然后只需复制洗牌后的值:
public static void Main(string[] args)
{
int[,] matrix = new int[5, 3];
Random rnd = new Random();
var values = Enumerable.Range(1, 3).ToList();
for (int row = 0; row < matrix.GetLength(0); row++)
{
values = values.OrderBy(x => rnd.NextDouble()).ToList();
for (int col = 0; col < matrix.GetLength(1); col++)
{
matrix[row, col] = values[col];
Console.Write(matrix[row, col] + " ");
}
Console.WriteLine();
}
Console.WriteLine("按Enter键退出。");
Console.ReadLine();
}
示例输出:
2 3 1
3 1 2
3 2 1
1 3 2
2 1 3
按Enter键退出。
英文:
You can make an List containing 1, 2, and 3, and then shuffle it for each row. Then just copy the shuffled values over:
public static void Main(string[] args)
{
int[,] matrix = new int[5, 3];
Random rnd = new Random();
var values = Enumerable.Range(1, 3).ToList();
for (int row = 0; row < matrix.GetLength(0); row++)
{
values = values.OrderBy(x => rnd.NextDouble()).ToList();
for (int col = 0; col < matrix.GetLength(1); col++)
{
matrix[row, col] = values[col];
Console.Write(matrix[row, col] + " ");
}
Console.WriteLine();
}
Console.WriteLine("Press Enter to Quit.");
Console.ReadLine();
}
Sample Output:
2 3 1
3 1 2
3 2 1
1 3 2
2 1 3
Press Enter to Quit.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论