So my aim:
put the value n
into a cell with smallest amount of instructions.
I could do +
twenty times for the value 20.
But a shorter way is for example to do >++++[<+++++>-]<
.
How could I calculate the optimized value setter (assuming that the cell is zero and I can only use this and the right cell) in python?
My thoughts so far: if I can find minimum values for a
, b
, and c
, so that a+b*c=my number
, then the algorithm would look like this:
>(b times +/-)[<(c times +/-)>-]<(a times +/-)
.
Plus or minus because of possibilities to wrap around 0<->255
well, I did it myself, however it is not a very nice code, since it checks all the possibilities for a number and return the smallest. I also included an offset option, so that the calcucating cell is not required to be the cell right to it (right to it == offset of 1).
def num ( number, off = 1 ) :
code = "[-]"
if not number : return code
char = "-" if number > 127 else "+"
number = ( 256 - number ) if number > 127 else number
table = { }
for i in range ( number ) :
loop = ( off * 4 + 3 + i + number // i ) if i else 0
if i :
if ( number % i ) <= ( ( - number ) % i ) :
mod = number % i
else :
mod = (( - number ) % i )
loop += 1
else :
mod = number
table [ i ] = loop + mod
mins = [ ]
for i in table :
if table [ i ] == min ( table.values ( )) : mins.append ( i )
m = min ( mins )
if m :
if ( number % m ) <= ( ( - number ) % m ) :
mchar = char
mod = number % m
app = number // m
else :
mchar = "+" if char == "-" else "-"
mod = (( - number ) % m )
app = number // m + 1
code += ">" * off + m * "+" + "[" + "<" * off
code += app * char + ">" * off + "-]" + "<" * off
code += mod * mchar
else :
mod = number
code += mod * char
return code
Edit: fixed small mistake for negative modulo calculation