Search code examples
brainfuck

Count if x ==y in Brainfuck


I'm trying to build a counter in brainfuck which count the appearance of '!' in any given input, if '!' Appear 3 times 'OK' should be printed out otherwise nothing should be printed. This is my Code:

+++ //0:'3'
[>++++++++++ ++++++++++ ++++++++++ +++  // a loop which compare each char in the given text with the '33*+'which means '!' saved in cell 1:'33'
 >,<
[->-<] <-] //and reducing the 3 in cell 0 -1
>>>++++++++++ ++++++++++ ++++++++++  // char 'o' in 2
  ++++++++++ ++++++++++ ++++++++++ 
  ++++++++++ ++++++++++ ++++++++++
  ++++++++++ ++++++++++ +
>  ++++++++++ +++++++++ ++++++++++ // char 'k' in 3
  ++++++++++ +++++++++ ++++++++++
  ++++++++++ +++++++++ ++++++++++
  ++++++++++ +++++++
<<<[->]>>.>.  // if false ok won't be printed .

now the problem above is that the counter counter each character, and not only '!'. My question here is, how can I specify that in Brainfuck?


Solution

  • There's only one comparison operator in BF. Comparing something to 0 (by using the [ and ] commands respectively).

    So to compare equality, you need to subtract one number from the other and check if the result is 0. If you're working with a brainfuck implementation that allows wrapping (subtracting 1 from 0 gives you the maximum value) then this is really easy, because you subtract one number form the other like so (assuming the values are in cells 0 and 1):

    >[<->-]<
    

    This ends with the result in cell 0, the pointer at cell 0 and cell 1 set to 0.

    From there, it's simple to check whether a value is 0. With the pointer still at cell 0, where the result of the subtraction is, you can do this:

    [ if the current value is not 0 
         your code goes here
         return back to cell 0
         [-] clear cell 0 so the "loop" exits after only one iteration
    ] exit the loop after only one iteration (if cell 0 was originally nonzero) and leave cell 0 with the value 0 inside
    

    If your brainfuck implementation doesn't support wrapping, you need to do this one step at a time. Subtract one from each number and check whether either of them are zero at each step (remember to copy the values around so they're not destroyed and you can still perform the next iteration). As soon as one of the values is zero terminate the loop. If the values are equal, at this point both values should be zero. I will leave the implementation of this algorithm as an exercise to you :)