brainfuck

how to set an array with the size of n to a specific number in brainfuck


I want to set an array of n elements to a predefined value (which isn't copying from a cell but setting a value from the code itself). How could I do that? without changing other cells as I went through after?


Solution

  • I assume by "an array" you mean a contiguous part of the brainfuck array; and that n is <256 so you can count on fitting n in a cell. In that case, beginning with the memory as "0 n ? ? ? ..." and the pointer at n, you could do something like:

    [>[-]<-[>+<-] ++++++++++ or whatever >]
    

    However, depending how you're going to manipulate this data later, it will often be a good idea to space it out more; e.g. to interleave it with 1s you could do

    [>[-]>[-]<<-[>>+<<-] ++++++++++ or whatever >+>]
    

    With regard to copying a chunk of the array to a different place, the best thing of all is to avoid needing to do that, but if you need to, here's one decent way to do it.

    [
      ->[>[>>]>+<<<[<<]>-]
      >[>>]>>[>>]+[<<]>
      [>[>>]<+<[<<]<<[<<]>+>[>>]>-]
      <<<[<<]+>>
    ]
    

    This assumes that the current memory layout is

    0 ? 1 a 1 b 1 c ... 1 z 0 0 0 ...

    where a, b, c, etc are an arbitrary number of arbitrary values, and it assumes that the pointer starts at the leftmost 1 cell. This would be a reasonable way to have set up the memory. In brainfuck it's crucial to choose your memory layout to make things easy for yourself. This code then copies this chunk of memory into the space at the right, producing

    0 ? 1 a 1 b 1 c ... 1 z 0 _ 1 a 1 b 1 c ... 1 z 0 ?

    where the '_' cell is also 0. This code assumes that the space to the right, that the data is being copied into, is already clear. In brainfuck, you don't want to clear space right before you use it, you want to clear data after you're done with it. You need to have a clear idea of what is where, at any given point in the execution, and not have the memory cluttered with things you've forgotten about.

    For each value, this code copies it to the '_' space between the arrays, then adds a 1 marker to the growing right array, then moves the value back to where it started and also into its place in the second array, then goes on to the next value. During the loop it keeps the 1 cell to the left of the value it's copying set to 0 as a marker, then resets it to 1 at the end. This code ends at the 0 cell left of the '_' cell.

    Note that if you then wanted to set all of the left "array" to, say, 10, you could just do

    <<[>[-]++++++++++<<<]