0

Given this array:

int a[] = {5, 8, 5, 6, 9, 5};

Would it be possible to remove all ints which equals 5 and move the rest the front of the array?

So that after the removal the array would look like this:

int a[] = {8, 6, 9, 0, 0, 0}

I don't know if by removing a element it becomes a 0 or a NULL?

Thanks!

MrEmper
  • 225
  • 1
  • 4
  • 18

4 Answers4

2

You can do it with two iterations over the array, first iteration two to turn the element you want to delete, second iteration to separate zeros from non-zeros.

    int a[] = {5, 8, 5, 6, 9, 5};
    int n = 6;
    for(int i = 0 ; i < n ; i++ ) {
        if(a[i] == 5 ) {
            a[i] = 0;
        }
    }
    int* zero = a;

    int* nonZero = a;
    int j = 0;

    while(j < n) {

        while(*zero != 0) {
            zero++;
        }       

        while(*nonZero == 0) {
            nonZero++;
            j++;
        }
        if(zero < nonZero) {
            *zero = *nonZero;
            *nonZero = 0;
        }
        j++;
    }
IBraheem.B
  • 21
  • 2
1

Your array is statically allocated, so always has the same size and deleted elements have the 0 value (according how you define the deleted values).

This link can help you and explains about how to delete element from array.

0

It is been awhile that i have programmed in C but it is posibble.

This is just a pseudo code, but you just need to change it to way of C programming.

int a[] = {5, 8, 5, 6, 9, 5};
int b[] = {5, 8, 5, 6, 9, 5}; // copy of array a to hold temp
for(int i = 0; i < Size of array; i++ ){
  for(int j = i; j < Size of array; j++ ){
    if(b[j] != 5){
       a[i] = b[j];
       a[j] = b[i];
       break;
    }
  }
}

It will be like (▼: Target to swap, F: Finished, X: Not a targe to swap, N: Not processed):

▼, ▼, N, N, N, N

5, 8, 5, 6, 9, 5

F, ▼, X, ▼, N, N

8, 5, 5, 6, 9, 5

F, F, ▼, X, ▼, N

8, 6, 5, 5, 9, 5

Result: 8, 6, 9, 5, 5, 5

And remove 5s, it is quite different depends what you mean. If you do not change size of array then they can be 0 or undefined(null). So I think it differs by how you program the function that returns array.

  • 2
    That is super inefficient in both space and time usage. Also how do you change the size of a statically sized array? That's not possible in standard C – UnholySheep Mar 16 '19 at 10:24
  • As far as I remember, he did not ask for performance. Well if you are that much experienced, what about you edit/write answer for everyone! :) And true, it is impossible to change statically sized array but if you create new array with diffrent size but having only numbers without 5s yes that work. So that is matter of how you program things in my opinion. Once again, we are not focusing on high performance optimization here. –  Mar 16 '19 at 11:30
0

your array is not dynamic so you just can't reduce its size after its been allocated.setting the value zero might solve the problem in your case.