Code patternsFirst movesSwap two cells

Swap two cells

Exchanges the values of two cells.

Watch it run

The form “Three moves” works on 3 cells, named “x”, “y” and “scratch”. Press Play, drag the step slider forwards and back, or change x and y with the sliders:

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

Three moves: x goes to the scratch cell, y goes to x, the scratch cell goes to y.

There is no way round the third cell. Each move empties its source, so one of the two values needs a place to wait.

The code

This is the program the figure ran. It is brainfuck as it stands: copy it, or open it in the playground, where you can change it:

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

What it needs

Common mistakes
  • Moving x onto y first. Then both values are mixed in one cell and cannot be separated.
  • Thinking the form without [-]-style moves is cheaper: the form With a subtraction (wrapping cells) on this page takes more plain steps whenever y is smaller than x.

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
Three moves7 + 12x + 5y4
With a subtraction (wrapping cells)7 + 17x + 5 × ((y − x) wrapped)4
Table 2. Measured when this page was written.
FormValuesBitsCharactersPlain stepsOptimised steps
Three movesx = 2; y = 7824664
Three movesx = 200; y = 1008242,9074
With a subtraction (wrapping cells)x = 2; y = 7828644
With a subtraction (wrapping cells)x = 7; y = 28281,3744

Other forms

With a subtraction (wrapping cells)

First y becomes y − x, then x becomes y − x, then the scratch cell rebuilds both. When y is smaller than x the middle loop runs almost once round the cell.

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

The form “With a subtraction (wrapping cells)” works on 3 cells, named “x”, “y” and “scratch”. Press Play, drag the step slider forwards and back, or change x and y with the sliders:

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.