Search code examples
brainfuck

How to Increment a 3 digit Number(User Input) by 1 in Brainfuck?


How to Increment a 3 digit Number by 1 in Brainfuck? For Example. Getting a User input of 699 this code should output 700.

This is something i Tried but its not working .

,>,>,+
<<.>.>.

Solution

  • The reason it doesn't work is because you don't have a 3 digit number in memory. You have three ASCII values from 48-57 (characters 0-9). I will explain how to do what you need to, but won't provider the actual BF code for multiplication etc, you can find those elsewhere.

    Let's call the characters X, Y and Z

    First of all we need to convert them to a number between 0 and 9. Assuming that the user enters digits only, we can do this by subtracting 48 (ASCII character 0) from the ASCII value.

    Ok so now we have three numbers from 0-9 as follows:

    A = X - 48
    B = Y - 48
    C = Z - 48
    

    Problem is they're still three separate digits and not one number. What's the actual number? In this case the number can be built in the following way:

    N = 100A + 10B + C
    

    So, you need to multiply A by 100, B by 10, C by 1, and then adding them all together. Could be done as follows:

    N = A
    N = (N * 10) + B
    N = (N * 10) + C
    

    After you've done that, you have an actual number in one cell, and you can increment it by doing N = N + 1 which in BF is a single +

    Now this would work for numbers up to 255, which is the largest number that a BF cell can hold. You want to work with larger numbers? It gets more complicated, because now you have to split that number up into two or more cells, propagating the carries yourself etc. I won't go into that here because that gets much more complex (though there are algorithms you can find online to help as well) and I think this is enough to get you started.

    EDIT: I realized that your code is also trying to print the incremented value. This requires more work, because the . command outputs the value of that cell as is as an ASCII character. But you need to output three digits. To do that you'd need to reverse the process above to split the number into three digits as follows:

    C = N % 10
    N = N / 10
    B = N % 10
    N = N / 10
    A = N
    

    Then you need to convert them from a number 0-9 to ASCII characters again as follows:

    X = A + 48
    Y = B + 48
    Z = C + 48
    

    and then finally you can output characters X, Y and Z in that order which would be the human readable incremented number.