如何在brainfuck中读取多位数字

时间:2012-01-17 17:03:35

标签: math brainfuck

我想用bf读取任意位数的数字。如果我手动设置,我知道如何读取正确的位数,如下所示:

,>,>, 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

但我宁愿能够在cell 0中设置一个数字,然后自动将每个数字的正确次数相乘。我最好做什么?

2 个答案:

答案 0 :(得分:1)

此链接应该非常有用:http://esolangs.org/wiki/brainfuck_algorithms

它包含乘法算法以及IF条件以及布尔比较(例如,检查用户是否按下输入[字符10]以结束输入。)

然后你做的就是这个(我会写一些伪代码,然后你可以使用那里描述的算法来实现它)。我将告诉你如何在最后实现一个while循环的伪代码,因为它不包含在那个页面中(但相当简单但相当简单)。当你设法准确理解每个角色正在做什么时,你一定会感到惊讶:D。无论如何,这里是:

你需要两个单元格A和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

这里有一些关于如何创建while循环的信息。假设您有以下代码:while (condition) {body}。我假设你设法使用我之前给你的链接来实现条件的代码。您需要一个单元格来存储条件的结果,我将其称为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 ]

答案 1 :(得分:0)

此程序用于读取n位数字并按原样打印。 始终保持n位数的最佳方法是将ascii作为序列存储在磁带中。

> +
[ - >,>+< 
  ----- -----    ; minus 10
  [              ; if enters means it is not a \n
    +++++ +++++  ; restore prev value
    < 
  ] >>           ; moving forward
]
                 ; numbers are 0 0 49 0 50 0 51
                 ; for input 123
<<<<[<<]         ; moving to the beginning
>>               ; reaching first char
[.>>]            ; just printing till end