gpt4 book ai didi

c# - 如何检查二维数组是否仅在 for 循环中是唯一的

转载 作者:太空宇宙 更新时间:2023-11-03 12:01:34 25 4
gpt4 key购买 nike

我将如何检查列和行的重复项并根据是否存在重复项返回 true 或 false。例如

1 2 3

3 1 2

2 3 1

会返回 true 因为没有重复,但是..

1 2 2

3 2 3

2 1 1

将返回 false,因为第 2 列 {2, 2, 1} 中存在重复项。

我将如何检查行中是否有重复项,然后检查列中是否有重复项?

我还需要检查每个数字以与同一行和同一列上的其他数字进行比较

到目前为止,我只有以下内容:

 for (int row = 0; row < n; row++)
{
for (int col = 0; col < m; col++)
{

Console.WriteLine("Check for: " + arr[row, col]);
for (int i = 1; i < arr.GetLength(1); i++)
{
Console.WriteLine("{0} == {1}", arr[row, col], arr[i, col]);
if (col != i)
{
if (arr[row, col] == arr[i, col])
{
unique = false;
}
}

}
for (int j = 1; j < arr.GetLength(0); j++)
{
Console.WriteLine("{0} == {1}", arr[row, col], arr[row, j]);
if (row != j)
{
if (arr[row, col] == arr[row, j])
{
unique = false;
}
}



}

自 2 天以来,我一直坚持该任务,我不知道如何对最后两个 for 循环进行正确检查。此外,我应该只使用 for 循环,并且只使用 2d 数组,既不是锯齿状的,也不是 HashSets 。

提前谢谢你。

嘿伙计们所以你们所有人都能够在仅使用for循环时从每个singel行和colum中检查每个数字以获得二维中的唯一矩阵你的行和列的for循环应该从0开始并且循环取决于对于行的宽度和高度的列然后最重要的是在 if 语句中所以当循环开始并检查检查列的索引和行的索引是否与它检查的数字相同必须继续,然后转到第二个 if 语句,如果行或列的索引与现在所在的行或列不同,并且行和列的数组 == 索引、列或列的数组行数组,索引然后矩阵不是唯一的。我也将发布代码,以便您可以看到最终结果。感谢所有帮助我引导我走向正确方向的人

for (int row = 0; row < arr.GetLength(0); row++)
{
for (int col = 0; col < arr.GetLength(1); col++)
{

Console.WriteLine("Check for: " + arr[row, col]);
for (int i = 0; i < arr.GetLength(0); i++)
{
if (i == row)
{
continue;
}
Console.WriteLine("{0} == {1}", arr[row, col], arr[i, col]);
if (i != row && arr[row, col] == arr[i, col])
{
unique = false;
}
}
for (int j = 0; j < arr.GetLength(1); j++)
{
if (j == col)
{
continue;
}
Console.WriteLine("{0} == {1}", arr[row, col], arr[row, j]);
if (j != col && arr[row, col] == arr[row, j])
{
unique = false;
}
}

}
}

最佳答案

我建议使用辅助方法来检查序列是否重复。您可以对行和列使用相同的算法。

        public bool SequenceHasDuplicateSymbols(char[] sequence) {

char symbolToCheckFor;
for (int i = 0; i < sequence.Length; i++)
{
symbolToCheckFor = sequence[i];

for (int j = 0; j < sequence.Length; j++)
{
if (i != j)
{
if (symbolToCheckFor == sequence[j])
{
return true;
}
}
}
}

return false;
}

关于c# - 如何检查二维数组是否仅在 for 循环中是唯一的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56808075/

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