LearnBuild toward a chatbotObstacle 2: two numbers from the tape

Obstacle 2: two numbers from the tape

Aim. At the end of this lesson your program multiplies −25 by −60 with both numbers on the tape, in under 60 steps.

Where the lessons are going

In lesson 3 the weight stood in the program, as plus signs. But a model also multiplies two numbers that only appear while it runs, and then neither of them can be written into the program.

The obvious way: a loop inside a loop

Try it: a is 6 and b is 7, both on the tape. Go to the last step. Then start again and step through a few rounds to see how it works:

Figure 1. A loop inside a loop. Watch "rounds done" count up to a while the total grows by b. (interactive)

Now with a number below zero

Try it: the sum has the product −25 × −60. Set a to −25 and b to −60, go to the last step and read how many steps it took:

Figure 2. The same program with your numbers. Watch the step counter when a is below zero. (interactive)

The way out, by hand

Try it: these are the bits of a = −25. Press every bit that is on. Each press adds b times the worth of that bit to the total:

b = −60. The leftmost bit counts as −128.

Total: 0

Figure 3. The eight bits of a. Each bit you press adds one line to the sum underneath. (interactive)

The same, as a program

Try it: go to the last step and compare the number of steps with the 327,557 of step 2:

−25 × −60Steps
Loop inside a loop, cells of this demo (16 bits)
Loop inside a loop, cells of the chat program (32 bits)
Shift and add, cells of the chat program

Measured here, except the row marked "worked out".

Figure 4. Shift and add as a program, with the three costs side by side (measured here, except the row marked "worked out"). (interactive)

What you can do now

Multiply any two numbers from the tape, below zero or not, for a few dozen steps. Every product of the sum can now be made, wherever its numbers come from. The second obstacle is gone.

All of this happened in the first few cells of the tape. A model has millions of numbers, spread over a very long tape, and brainfuck cannot say "go to cell 5,000". What then?

How the real program differs

When the plain loop wins. For a very small a that is not below zero, a few rounds are cheaper than reading eight bits. But the program is written before the numbers are known. Shift and add costs about the same every time, so it is the safe choice wherever numbers can be large or negative.

A bonus. Peeling a is most of the work. When the same a must be multiplied by many different numbers, a is peeled once, and every extra product costs only a step or two for each bit that is on. The chat program uses exactly that for its scores: see the note "Where the scores come from" of lesson 10.

The 21 billion of step 2. 4,294,967,271 rounds of 5 steps. The 5 steps a round were measured on the smaller cells; the large case was not run.