Simvik

Search a calibration table

Find the table entry at or below a reading. A medium embedded C problem (Arrays and strings), run and graded in the browser.

medium · Arrays and strings · lookup-table · binary-search

Sensor linearisation uses a table of breakpoints sorted in ascending order. To interpolate, you first need the segment a reading falls in.

Return the index of the last entry of table that is less than or equal to key. Return -1 if key is below the first entry or the table is empty. The table has n entries with no duplicates.

Starter code

int lut_floor_index(const uint16_t *table, size_t n, uint16_t key) {
  // Index of the largest entry <= key, or -1.
  return -1;
}

Example tests

Between two breakpoints

const uint16_t t[] = { 100, 200, 400, 800 };
printf("%d\n", lut_floor_index(t, 4, 250));

Expected output:

1

Exactly the last breakpoint

const uint16_t t[] = { 100, 200, 400, 800 };
printf("%d\n", lut_floor_index(t, 4, 800));

Expected output:

3

Learn it first

  • Arrays and strings · Decay, bounds, safe copying, and parsing and formatting without the heap.

More Arrays and strings problems