-2

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 = 0;
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...

BladeMight
  • 2,670
  • 2
  • 21
  • 35

1 Answers1

1
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++;
}
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
vivek kv
  • 406
  • 6
  • 11