gpt4 book ai didi

c# - 将整数列表打印为矩阵

转载 作者:行者123 更新时间:2023-11-30 13:35:30 24 4
gpt4 key购买 nike

我有一个包含 9 个整数的列表,我想将列表中的所有元素打印为矩阵 3,3。而且我必须避免在每一行的末尾出现不必要的空白。是否可以使用 String.Join ?谢谢。

这是我的代码:

int[] input = Console.ReadLine().Split().Select(int.Parse).ToArray();

int[][] matrix = new int[input[0]][];

for (int i = 0; i < input[0]; i++)
{
int[] line = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();

matrix[i] = line;
}

List<int> arr = new List<int>(9);
List<int> arr1 = new List<int>(9);

arr = Enumerable.Repeat(0, 9).ToList();

//for (int i = 0; i < 9 ; i++) sum[i%3, i/3] = 0;

for (int row = 0; row < input[0] - 2; row++)
{
for (int col = 0; col < input[1] - 2; col++)
{
arr1.Add(matrix[row][col]);
arr1.Add(matrix[row][col + 1]);
arr1.Add(matrix[row][col + 2]);
arr1.Add(matrix[row + 1][col]);
arr1.Add(matrix[row + 1][col + 1]);
arr1.Add(matrix[row + 1][col + 2]);
arr1.Add(matrix[row + 2][col]);
arr1.Add(matrix[row + 2][col + 1]);
arr1.Add(matrix[row + 2][col + 2]);

if (arr1.Sum() > arr.Sum())
{
arr = arr1.Select(a => a).ToList();
}
arr1.Clear();
}
}

Console.WriteLine($"Sum = {arr.Sum()} ");

// print the list as a matrix

最佳答案

这就是我使用 String.Join 打印它的方式:

List<int> asd = new List<int> {1,2,3,4,5,6,7,8,9};

for (int i = 0; i < asd.Count; i +=3)
{
Console.WriteLine(string.Join(" ",asd.Skip(i).Take(3)));
}

解释:步长为3,跳过等于stepsize的数,取3合并矩阵的一行。

关于c# - 将整数列表打印为矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53283416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com