>>>>,[[<]<<+>>>[>],]<[<]<+<[>>+<[-<-<+>>]<<++[->>+<<]>]>[-]>>[<[->.[-]<[->+<]<+[->+<]>>]++++++++++.[-]<[->+<]>>]
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.
Can we assume that the input will never have new lines? – MayorMonty – 2016-08-06T02:13:47.507
@MayorMonty yep. – acrolith – 2016-08-06T02:20:21.007
2Can we output array of strings instead? – Leaky Nun – 2016-08-06T05:10:09.673
@LeakyNun no 15 chars – acrolith – 2016-08-06T16:58:13.317
2May we print with a trailing newline? – Giuseppe – 2017-10-04T15:53:54.877
Can it be a function or only full programs are allowed? – val says Reinstate Monica – 2019-07-09T14:01:54.967
Also, can we assume ASCII or UTF-8 support is required? – val says Reinstate Monica – 2019-07-09T14:03:46.200