Infinite Counting Loop in Brainfuck
Asked Answered
S

2

7

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

+[[>+]+]

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

My issue is, when it gets to 255, the inner loop increments the cell to 0, and then the outer loop increments it to 1 immediately. This acts as a 'double step' when it overflows, instead of a single step. This is the only way I could get the loop to continue infinitely with this tight of a program.

The count for each cell goes 0 -> 1 -> 2 ... 254 -> 255 -> 1 ...

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

It is just hard to continue a loop when the current cell is zero. I have played with variations on the same theme, but none of them get it just right.

This particular program is just a trivial counting program for testing, but what will really help me with future programs is knowing how to invert the looping conditional like I need to to make this counting loop work.

Solemnity answered 7/9, 2011 at 22:54 Comment(0)
C
4

Try:

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

After the first inner loop we know the data is 0 followed by a bunch of 255's. Move to the next cell and increment them all until we get back to the start. Then increment the first cell and start all over.

Calm answered 7/9, 2011 at 23:21 Comment(1)
Unfortunately it adds around 62% to the length of your program, and it is much less elegant, but it works. I am not convinced there isn't a shorter way, but this is probably the most obvious.Calm
C
2

Another possibility I considered last night, although it is a bit different than your requirements:

-[[-]>-]

It is the same size as your original, but it counts down. It cycles each cell from 255 down to zero, but only modifies one cell at a time. I thought I'd add it as it is an interesting, short loop that you can use for testing.

You can of course make any of these loops count up or down exclusively by using only + or only -.

Calm answered 8/9, 2011 at 15:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.