3

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

dev_null
  • 71
  • 6
  • Are you looking to optimize for size of the program or for number of calculations? – Adalcar Apr 22 '21 at 09:04
  • @Adalcar said in the first line: want to have the minimum amount of instructions, by that I mean the Brainfuck instructions <>+- and [ ]. – dev_null Apr 22 '21 at 18:26

2 Answers2

1

https://esolangs.org/wiki/Brainfuck_constants gives the shortest known ways to get different values (marked as to how many cells they use and whether they rely on wraparound on overflow). To equal all the ones that use only two cells, your program will need to be a bit more complicated but it looks doable.

  • 1
    Thank you! Though, I don't want to hardcode all possibilities, till yet, only my code was able to do so – dev_null Apr 27 '21 at 14:39
  • Yeah, I was thinking you wouldn't need to hardcode all possibilities, but just redo your template. Since you're assuming byte cells, I think all the shortest ones are either of the form ">a[c] – Daniel Cristofani Apr 28 '21 at 23:09
0

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

dev_null
  • 71
  • 6