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:
[->>+<<]>[-<+>]>[-<+>]<<
What it needs
- One scratch cell that is zero; it is zero again at the end.
- Any cell size for the main form. The form With a subtraction (wrapping cells), which is the one from the wiki, needs wrapping cells.
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
| Form | Plain steps | Optimised steps |
|---|---|---|
| Three moves | 7 + 12x + 5y | 4 |
| With a subtraction (wrapping cells) | 7 + 17x + 5 × ((y − x) wrapped) | 4 |
| Form | Values | Bits | Characters | Plain steps | Optimised steps |
|---|---|---|---|---|---|
| Three moves | x = 2; y = 7 | 8 | 24 | 66 | 4 |
| Three moves | x = 200; y = 100 | 8 | 24 | 2,907 | 4 |
| With a subtraction (wrapping cells) | x = 2; y = 7 | 8 | 28 | 64 | 4 |
| With a subtraction (wrapping cells) | x = 7; y = 2 | 8 | 28 | 1,374 | 4 |
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.
[->>+<-<]>[-<+>]>[-<+<+>>]<<
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
- A stack, in its form "Swap the two top items".
- Sorting exercises in the challenges.
Sources
- Source: Esolang wiki: Brainfuck algorithms: section "swap x, y", both forms.
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.