>>>>,[[<]<<+>>>[>],]<[<]<+<[>>+<[-<-<+>>]<<++[->>+<<]>]>[-]>>[<[->.[-]<[->+<]<+[->+<]>>]++++++++++.[-]<[->+<]>>]
Try it online!
Safe in flavours of BF that does not mask the cells with 256
, does not support null bytes.
Remove the initial right arrows if the flavour supports negative memory for 4 bytes saved.
Explanation
The program is divided into 3 stages:
Stage 1: >>>>,[[<]<<+>>>[>],]<[<]
Stage 2: <+<[>>+<[-<-<+>>]<<++[->>+<<]>]>[-]>>
Stage 3: [<[->.[-]<[->+<]<+[->+<]>>]++++++++++.[-]<[->+<]>>]
Stage 1
In this stage, we put all the characters onto the tape, while keeping count of the number of characters.
This is the tape for the input abcdefghi
after this tape:
000 009 000 000 095 096 097 098 099 100 101 102 103
^
The 009
is the count.
For each character, we move the the first zero on the left [<]
and then add one to the count <<+>>>
, and then move to the rightmost zero [>]
to get ready for the next character.
Stage 2
This stage does the square root of the length stored in the second cell.
It keeps subtracting by 1, 3, 5, 7, ...
until the number reaches zero, while keeping check of the number of iterations.
It works because square numbers can be expressed as 1 + 3 + 5 + ...
.
Stage 3
Denote the square root of the length found above as n
.
This stage outputs n
characters at a time, and then output a newline, until the tape is cleared.