Andrew
Andrew

Reputation: 15

Shifting array to replace removed element

I am supposed to get the output 8, 6. But I get 8,9 when this code is run. Why am I getting the out put 8,6 and how can I fix the code to make the output become 8,9.

int inputarray[]={9,8,9,9,9,9,6};
int length = 7;
int value = 9;

void arrayShift(int arr[], int length, int value)
{
    for(int i = 0; i<length; i++)
    {
        if(arr[i] == value)
            {
                for (int k = i; k<length ; k++)
                    {
                        arr[k] = arr[k+1];
                    }
        arr[length-1] = 0;

            }       
    }
}

Upvotes: 0

Views: 1262

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Your algorithm for shifting is wrong: you fail to adjust i on removal. In addition, it is rather inefficient: you can do this in a single loop with two indexes - r for reading and w for writing. When you see the value you want to keep, adjust both the reading and the writing index. Otherwise, increment only the reading index.

Once the reading index reaches the count, the writing index indicates how many items you have left. You need to return it to the caller somehow, otherwise he wouldn't know where the actual data ends. You can return the new length as the return value of your function, or take length as a pointer, and adjust it in place.

int arrayShift(int arr[], int length, int value) {
    int r = 0, w = 0;
    for (; r != length ; r++) {
        if (arr[r] != value) {
            arr[w++] = arr[r];
        }
    }
    return w;
}

Here is how you call it:

int inputarray[]={9,8,9,9,9,9,6};
int length = 7;
int value = 9;
int newLen = arrayShift(inputarray, length, value);
for (int i = 0 ; i != newLen ; i++) {
    printf("%d ", inputarray[i]);
}
printf("\n");

Demo.

Upvotes: 1

keltar
keltar

Reputation: 18399

When shifting array, you may replace first element (containing number equal to value) with the same value from other element. In that case, you need to restart iteration on this element again, e.g.:

void arrayShift(int arr[], int length, int value)
{
    for(int i = 0; i<length; i++)
    {
        if(arr[i] == value)
        {
            for (int k = i; k<length-1 ; k++)
            {
                arr[k] = arr[k+1];
            }

            arr[length-1] = 0;
            i--;   // <-- this
        }
    }
}

Upvotes: 4

Related Questions