Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 479
Jolof Avatar asked Mar 05 '26 21:03

Jolof


2 Answers

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

result

like image 50
Pavel Anikhouski Avatar answered Mar 07 '26 09:03

Pavel Anikhouski


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;
}
like image 28
Peter Petukhov Avatar answered Mar 07 '26 11:03

Peter Petukhov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!