C# 矩阵元比较
我在比较矩阵元素时遇到了一些问题。代码如下:C# 矩阵元比较,c#,matrix,C#,Matrix,我在比较矩阵元素时遇到了一些问题。代码如下: int coll = 0; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { int tmp = 0; for (int k = 0; k < 9; k++) { if (matrix[i, j] == matrix[i, k]) {
int coll = 0;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
int tmp = 0;
for (int k = 0; k < 9; k++)
{
if (matrix[i, j] == matrix[i, k])
{
tmp++;
Console.WriteLine("{0},{1} coll {2},{3}-al", i, j, i, k);
}
coll += tmp;
}
}
}
0:0位置将仅与自身碰撞,而不会与1:0碰撞。有人能告诉我为什么吗?试试这个逻辑:
class Program
{
static void Main(string[] args)
{
int[,] matrix=new int[,] {
{ 1, 2, 3, 4 },
{ 1, 3, 4, 2 },
{ 2, 3, 4, 1 },
{ 2, 4, 1, 3 } };
// This returns the #of collisions in each column
Debug.WriteLine(CheckColumn(matrix, 0)); // 2
Debug.WriteLine(CheckColumn(matrix, 1)); // 1
Debug.WriteLine(CheckColumn(matrix, 2)); // 1
Debug.WriteLine(CheckColumn(matrix, 3)); // 0
}
static int CheckColumn(int[,] matrix, int column)
{
int[] data=new int[matrix.GetLength(0)];
for(int i=0; i<data.Length; i++)
{
data[i]=matrix[i, column];
}
var hist=data.GroupBy(i => i)
.OrderByDescending(g => g.Count())
.Select(g => new { Num=g.Key, Dupes=g.Count()-1 })
.Where(h=>h.Dupes>0);
return hist.Count()>0?hist.Sum(h=>h.Dupes):0;
}
}
我使用了矩阵的定义是什么?矩阵是9x9?在数独解算器上工作?矩阵的类型是什么?是int[,]还是object[,]?移动coll+=tmp;在内部循环之外。我正在做一个数独解算器,但首先我需要生成一个具有特定规则的表。矩阵为int[,]。我使用整数列表来避免行中的冲突,并使生成速度更快。但它和矩阵一样包含整数值。感谢您的回复,我将尝试一下:
class Program
{
static void Main(string[] args)
{
int[,] matrix=new int[,] {
{ 1, 2, 3, 4 },
{ 1, 3, 4, 2 },
{ 2, 3, 4, 1 },
{ 2, 4, 1, 3 } };
// This returns the #of collisions in each column
Debug.WriteLine(CheckColumn(matrix, 0)); // 2
Debug.WriteLine(CheckColumn(matrix, 1)); // 1
Debug.WriteLine(CheckColumn(matrix, 2)); // 1
Debug.WriteLine(CheckColumn(matrix, 3)); // 0
}
static int CheckColumn(int[,] matrix, int column)
{
int[] data=new int[matrix.GetLength(0)];
for(int i=0; i<data.Length; i++)
{
data[i]=matrix[i, column];
}
var hist=data.GroupBy(i => i)
.OrderByDescending(g => g.Count())
.Select(g => new { Num=g.Key, Dupes=g.Count()-1 })
.Where(h=>h.Dupes>0);
return hist.Count()>0?hist.Sum(h=>h.Dupes):0;
}
}