如何在2D数组中水平和垂直检查重复值? [英] How to check duplicate values horizontally and vertically in a 2D array?

查看:49
本文介绍了如何在2D数组中水平和垂直检查重复值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个像这样的数组:

Let's say I have an array like this :

9 1 2 0 
1 5 2 5 
7 1 6 3 
4 3 2 7 

我希望能够创建一个垂直和水平遍历数组的循环,以查看是否存在重复项.
例如,它将首先检查9 1 7 4以查看是否有公仔.然后是1 5 1 3,依此类推.
之后,它将执行9 1 2 0(这将告诉我有一个重复),然后是1 5 2 5 7,等等.
我该怎么办?

I want to be able to create a loop that goes through the array vertically and horizontally to see if there's any duplicates.
For example, it will first check 9 1 7 4 to see if there's a dups. Then 1 5 1 3 and so on.
After that, it'll do 9 1 2 0 (which will tell me there's a dup), then 1 5 2 5 7, etc etc.
How can I do that?

推荐答案

在可能的情况下,嵌套循环解决方案可能不是解决问题的更直接的方法.在这种情况下,使用LINQ必须更容易:

While possible, a nested loops solution may not be the more straightforward way of solving it. In this case, using LINQ is must easier :

var matrix = new int[4, 4]
{
    { 9, 1, 2, 0 },
    { 1, 5, 2, 5 },
    { 7, 1, 6, 3 },
    { 4, 3, 2, 7 }
};

for (int i = 0; i < 4; i++)
{
    var row = Enumerable.Range(0, 4).Select(x => matrix[i, x]);
    if (row.Distinct().Count() != 4)
        Console.WriteLine("Duplicated value in row {0} : {1}", 
            i + 1, string.Join(", ", row));
}

for (int i = 0; i < 4; i++)
{
    var column = Enumerable.Range(0, 4).Select(x => matrix[x, i]);
    if (column.Distinct().Count() != 4)
        Console.WriteLine("Duplicated value in column {0} : {1}", 
            i + 1, string.Join(", ", column));
}

输出:

Duplicated value in row 2 : 1, 5, 2, 5
Duplicated value in column 2 : 1, 5, 1, 3
Duplicated value in column 3 : 2, 2, 6, 2

这篇关于如何在2D数组中水平和垂直检查重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆