I want to read in a number with any number of digits with bf. I know how to read in the correct number of digits if I set it manually, like this:
,>,>, 2 Read in 3 digits
<< 0
--------
--------
--------
--------
--------
-------- 45 decrements
> 1
--------
--------
--------
--------
--------
--------
> 2
--------
--------
--------
--------
--------
--------
[>+<-]< 1 Copy digit 3 to cell 3
[>>++++++++++<<-]< Copy 10 * digit 2 to cell 3
Copy 100 * digit 1 to cell 3
[>>>>++++++++++ 4
[<++++++++++>-] 4
<<<<-]>>> 3
>++++++++++..< Add 2 line breaks
., Print and Pause
But I'd rather be able to set a number in cell 0
and then automatically multiply the right number of times for each digit. What would I be best off doing?
2-digit numbers are the numbers that have two digits and they start from the number 10 and end on the number 99. They cannot start from zero because in that case it will be considered as a single-digit number. The digit on the tens place can be any number from 1 to 9. For example, 45, 78, 12 are two-digit numbers.
This link should be quite helpful: http://esolangs.org/wiki/brainfuck_algorithms
It contains algorithms for multiplication and also an IF condition as well as boolean comparisons (to check if, for example, the user pressed enter [character 10] to end the input.)
Then what you do is this (I will write some pseudocode and then it's up to you to implement it using the algorithms described there). I will tell you also give pseudocode on how to implement a while loop at the end since that is not included in that page (but pretty simple nonetheless... relatively). You will definitely be amazed when you manage to understand exactly what each character is doing :D. Anyway, here goes:
you need two cells A and B
move to B
input a character
while B is not equal to 10 (the newline character) then
subtract 48 from B ('0' is character 48, so if we subtract 48 from any digit entered we should get its value. Of course this assumes that the user only presses digit keys or enter. I'll leave it as an exercise to you to do error checking)
multiply A by 10
add B to A (you can just move B to A like this [<+>-] since you will not need B's value anymore)
move to B
input a character
And here's a bit of info about how to create a while loop. Suppose you have this code: while (condition) {body}
. I will assume you managed to implement the code for the condition using the link I gave you earlier. You need a cell in which to store the result of the condition, which I'll call C
execute condition and store result in C
start loop using [[-] (start the loop and immediately clear C)
execute loop body
execute condition and store result in C
end loop using ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With