LearnCode patterns

Code patterns

Short pieces of brainfuck that each do one job: move a number, copy it, decide, calculate, print. Run each one, step through it, change its values, copy it.

One pattern at work

The program below copies the number in the first cell into the second cell and keeps it in the first. Press Play, drag the step slider forwards and back, or change x:

The figure needs JavaScript.

Notice that the number never travelled in one piece. The first loop emptied x and gave each unit to two cells at once, the copy and the third cell. The second loop poured the third cell back into x. A cell can only be read by emptying it, so a copy needs a helper that starts and ends at 0. A helper like that is a scratch cell.

This program is a code pattern: a short piece of brainfuck that does one job, written so that every cell starts and ends in a known state. Every pattern here has a figure like this one, the program to copy, what it costs, and other forms of the same job. The marks you saw are the same everywhere: the pointer is the cell with the heavy edge and the triangle, and a cell in bold has just changed.

Words used on the pattern pages
Pointer
The cell the program is working on. A pattern says where it must start and where it ends.
Read, changed, put back
In the small drawings below: “read” means the program looks at the cell, “changed” means it holds a new value at the end, and “put back” means it was used on the way and holds its old value again.
Scratch cell
A helper cell. It must be zero before the pattern runs, and the pattern leaves it zero. The tests check both.
Cost
How many steps the pattern takes. A plain step is one command. An optimised step is counted by an interpreter that folds simple loops. The two can differ a thousand times; What costs what shows why.
Cell size
Most patterns work on any cell size. Where a pattern needs cells that wrap round, or a fixed width of 8, 16 or 32 bits, its page says so under “What it needs”.

38 patterns follow, 111 forms in all. Which job do you need?

Find a pattern

38 patterns, 111 forms. Every one is tested.

Under each pattern is the tape before and after its first form, for the values in its figure.

I want to put a value somewhere First moves

I want to decide or repeat Control

I want to calculate Arithmetic

I want to keep many values Data

I want to read or print Input and output

I want it to be fast on large numbers Advanced: wrapping cells of a known width

Where to go next