Remove items from an array by position, closing the gap each time.
What to build
A program that deletes from an array by shifting the later items left.
Requirements
- Carry out the deletions in the order given. Each position refers to the array as it is at that moment.
- Ignore a position that is not in the array.
- Print the numbers that are left, or
emptyif none are.
Input
The first line has n, and the second has the n numbers. The third line has q, and the fourth has the q positions.
Output
The remaining numbers on one line, separated by spaces, or empty.
Constraints
1 ≤ n ≤ 100 and 1 ≤ q ≤ 100.
Example
Input:
5
10 20 30 40 50
2
1 2
Output:
10 30 50
Why it works
An array has no holes, so every item after the deleted one must move one place left. That shifting is why deleting from an array costs O(n).
Examples
Example 1 · Input
5 10 20 30 40 50 2 1 2
Expected output
10 30 50
Example 2 · Input
3 1 2 3 2 5 0
Expected output
2 3
Hints
Hint 1
To delete position pos, copy each later item one place to the left, then lower the count.
Hint 2
A position is valid only when it is at least 0 and less than the current count.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
int main(void) {
int n, q, a[100];
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
scanf("%d", &q);
for (int k = 0; k < q; k++) {
int pos;
scanf("%d", &pos);
if (pos < 0 || pos >= n) continue;
for (int i = pos; i < n - 1; i++) a[i] = a[i + 1];
n--;
}
if (n == 0) printf("empty");
for (int i = 0; i < n; i++) {
if (i > 0) printf(" ");
printf("%d", a[i]);
}
printf("\n");
return 0;
}