Library contents

C Compact an array in place

Retain the stock bins that still contain items to pick.

A simple example

Compact an array in place

  1. Start with 1, 2, 3
  2. Do this Remove values below 2
  3. Result 2, 3
The rule rejects only the first value. The surviving pair stays in order.

Syntax

C syntax
counts[kept++] = counts[i]
Run these examples in C

Save one example at a time as lesson.c. Use C17 and a Unix-style shell.

cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lesson

Clear empty stock bins from the pick list

A stockroom prints only bins that contain items a picker can collect. Empty bins appear twice in today's count, and both should disappear while the remaining quantities keep their order.

From the programint counts[] = {4, 0, 2, 0}
Result4, 2
lesson.c
#include <stdio.h>

int main(void) {
    int counts[] = {4, 0, 2, 0};
    size_t kept = 0;
    for (size_t i = 0; i < sizeof counts / sizeof counts[0]; ++i) {
        if (counts[i] != 0) counts[kept++] = counts[i];
    }
    for (size_t i = 0; i < kept; ++i) printf("%s%d", i ? ", " : "", counts[i]);
    return 0;
}
Output
4, 2

Both zeros are excluded and the positive counts stay in order.

Advertisements

Count packs on the delivery slip

A loading desk receives four item counts in sequence. Only positive quantities go to the packing desk. Which entries survive, in their original order?

Given6 · 2 · 6 · 0
Worked result6 · 2 · 6

Review print quantities

A print room records four job quantities, including a cancelled job. Only positive quantities go to the packing desk. Which entries survive, in their original order?

Given3 · 0 · 8 · 3
Worked result3 · 8 · 3

What to watch for

Only the prefix through the new used length contains the filtered result. Array capacity stays the same.

Documentation for Compact an array in place