Infinite Counting Loop in Brainfuck

As a debugger / test program for my implementation of brainf * ck, I created the following counting loop:

+[[>+]+] 

With one byte, wrapping cells and 30k cells with wraparound, this creates an endless loop of counting. It sets each cell to 1, then each cell to 2, etc.

My problem is that when it reaches 255, the inner loop increments the cell to 0, and then the outer loop instantly increments it to 1. This acts like a β€œdouble step” when it overflows instead of a single step. This is the only way I could get the loop to continue indefinitely with this program.

The score for each cell is 0 -> 1 -> 2 ... 254 -> 255 -> 1 ...

Although I would like it to go 0 -> 1 -> 2 ... 254 -> 255 -> 0 -> 1 ...

Just continue the loop when the current cell is zero. I played with variations on the same topic, but none of them could handle it.

This particular program is just a trivial counting program for testing, but what really helps me in future programs is to know how to invert the loop condition, as if I need to do this counting cycle.

+6
source share
2 answers

Try:

+[[>+]>[+>]+]

After the first inner loop, we know that the data is 0, and then a group of 255. Move to the next cell and increase them until we return to the beginning. Then add the first cell and start over.

+4
source

Another possibility that I considered last night, although it is slightly different from your requirements:

 -[[-]>-] 

This is the same size as your original, but it is being counted. It cycles every cell from 255 to zero, but only changes one cell at a time. I thought I would add it as this is an interesting short loop that you can use for testing.

You can, of course, do any of these cycles up or down with just + or only.

+1
source

Source: https://habr.com/ru/post/896834/


All Articles