Code patternsDataWalk an array of records

Walk an array of records

Does the same job on every record of a row, with one copy of the program.

Watch it run

The form “A job on every record” works on 13 cells; the named ones are “zero”, “flag”, “a”, “b” and “end”. Press Play, drag the step slider forwards and back, or edit the a of each record:

The figure needs JavaScript. The program below is the result for the example values.

Brainfuck moves are relative: "two cells to the right of here". So a piece of program written for one record works on any record, if the pointer stands on that record's first cell.

Every record starts with a flag that is 1. The loop does the job, steps one record to the right and tests the next flag. The first empty flag ends the walk.

A zero cell before the first record lets [<<<] walk home again.

The code

This is the program the figure ran. The pointer starts on “flag” (cell 3). It is brainfuck as it stands: copy it, or open it in the playground, where you can change it:

[>[->++<]>>]<<<[<<<]>>>
Open in the playground23 characters

What it needs

Common mistakes
  • A job that ends on another cell of the record than it started on. The step to the next record then lands in the wrong column.
  • A zero in the flag column inside the row: the walk stops there.

What it costs

A plain step is one command. An optimised step is one step of an interpreter that folds runs of the same command and flat loops. Choose the values and watch the two bars; What costs what explains how cost is counted:

The figure needs JavaScript. The table below has the measured steps.

Cost as a formula, and measured
Table 1. The cost as a function of the values. Exact formulas are checked on every case they run.
FormPlain stepsOptimised steps
A job on every recordgrows with the values3 + 3 per record
A running total that travels alonggrows with the values1 + 3 per record
Table 2. Measured when this page was written.
FormValuesBitsCharactersPlain stepsOptimised steps
A job on every recorda = 3, 1, 48238312
A job on every recorda = 9, 9, 9, 9, 982332318
A running total that travels alonga = 3, 1, 482119410

Other forms

A running total that travels along

Adds up the a of every record. The total moves from record to record in the third cell and ends just past the last record.

[>[->+<]>[->>>+<<<]>]
Open in the playground21 characters
Run this form step by step

The form “A running total that travels along” works on 15 cells; the named ones are “zero”, “flag”, “a”, “carry”, “end” and “total”. Press Play, drag the step slider forwards and back, or edit the a of each record:

The figure needs JavaScript. The program below is the result for the example values.

Where it is used

Sources

Every program on this page was run on many inputs, in plain and in optimised mode, and compared with JavaScript. The explanations are written for this page.