BladeMight BladeMight - 3 months ago 4
C# Question

Replace two items that are next to each other with one item in array

Is there a way to replace two items that are next to each other with one item in array.

In array like this:

int[] array = new int[]{ 1, 2, 2, 3, 3, 4, 5, 3, 2 };


remove same items which are next to each other, resulting into this:

{ 1, 2, 3, 4, 5, 3, 2 };


Edit:
Here what i end up with:

int[] array = new int[]{ 1, 2, 2, 3, 3, 4, 5, 3, 2 };
int last = null;
List<int> fixed = new List<int>();
foreach(var i in array)
{
if(last == 2 && i == 2 ||
last == 3 && i == 3 ||)
{
}
else
{
fixed.add(i);
last = i;
}
}
return fixed.ToArray() // Will return "{ 1, 2, 3, 4, 5, 3, 2 }"


but i must enter all the ones i want to skip...

Answer
int[] array = new int[] { 1, 2, 2, 3, 3, 4, 5, 3, 2 };
//int[] output = array.Distinct().ToArray();Use this line if you want to remove all duplicate elements from array
int j = 0;
while (true)
{
    if (j + 1 >= array.Length)
    {
        break;
    }
    if (array[j] == array[j + 1])
    {
        List<int> tmp = new List<int>(array);
        tmp.RemoveAt(j);
        array = tmp.ToArray();
    }
    j++;
}
Comments