简体   繁体   中英

C# remove duplicates from jagged array

I am writing an algorithm for university. And I have almost everything except the last thing. I now have jagged array of numbers, example of this array:

[0][1]
[1][11,12]
[2][3,7,11,15]
[3][6,7,10,11]

And i need to remove duplicates, like delete every number from all next rows, that is present in the previos row. Output should be something like this:

[0][1]
[1][11,12]
[2][3,7,15]
[3][6,10]

I have tried something like this:

for (int i = 0; i <= numbers.Length + 1; i++)
{
    int size = numbers[i].Length;
    for (int j = 0; j < size; j++)
    {
        if (numbers[i][numbers[i].Length] != numbers[i + 1][numbers[i + 1].Length])
        {
            newNumbers[i][j] = numbers[i][j];
        }
    }
}

But it does not work the way it should.

You can solve it by using Except method from System.Linq namespace.

At every loop iteration go through all next rows and get the difference between these rows and current one and reassign it back. It's possible, because jagged array is an array whose elements are arrays and you have the same int data type for all items

int[][] jaggedArray = new int[4][];

jaggedArray[0] = new[] { 1 };
jaggedArray[1] = new[] { 11, 12 };
jaggedArray[2] = new[] { 3, 7, 11, 15 };
jaggedArray[3] = new[] { 6, 7, 10, 11 };

for (int i = 0; i < jaggedArray.Length; i++)
{
    var currentRow = jaggedArray[i];
    for (int j = i + 1; j < jaggedArray.Length; j++)
    {
        var result = jaggedArray[j].Except(currentRow);
        jaggedArray[j] = result.ToArray();
    }
}

If you print the result array

foreach (var array in jaggedArray)
{
    foreach (var item in array) 
        Console.Write($"{item} ");

    Console.WriteLine();
}

The output will be the following

结果

public static int[][] RemoveDuplicates(this int[][] data)
{
    var result = new int[data.Length][];
    var used = new List<int>();

    for (int i = 0; i < data.Length; i++)
    {
        var hashSet = new HashSet<int>(data[i].Except(used));
        result[i] = hashSet.ToArray();
        used.AddRange(hashSet);
    }
    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM