2016-12-07 49 views
0

我試着編寫一個brainfuck程序,要求用戶輸入兩個數字(小於10)來計算這些數字的乘積。計算完成後,應打印結果。我的代碼如下所示:Brainf * ck的乘法

++++[>++++[>+++<-]<-] writing 48/0x30/'0' in cell(2) 
    ,>,>     reading two numbers in cell(0) and cell(1) 
    [<-<->>-]    decrementing cell(0) and cell(1) by 48/0x30/'0' 
    <<      go to cell(0) 
    [      muliplication loop 
     >     go to cell(1) 
     [>+>+<<-]   move cell(1) to cell(2) and cell(3) 
     >>     go to cell(3) 
     [<<+>>-]   move cell(3) back to cell(1) 
     <<<-    decrement cell(0) 
    ] 
    ++++[>++++[>+++<-]<-] adding 48/0x30/'0' to cell(2) 
    >>.      print result 

這讓我真的很奇怪的結果:

0 * 1 = 3 
1 * 1 = 4 
1 * 2 = 8 
2 * 1 = 5 
2 * 2 = : 

等。

當然,實際輸出看起來像這樣:

​​

,但我想顯示在這裏更具可讀性。

回答

0

經過一番考慮後,我意識到當我將結果修改爲可打印的數字時,我犯了一個大錯誤。我使用cell(1)作爲臨時計數器單元,儘管它仍然有價值。所以我加入48/0x30/'0'的結果之前插入>[-]<

++++[>++++[>+++<-]<-] writing 48/0x30/'0' in cell(2) 
    ,>,>     reading two numbers in cell(0) and cell(1) 
    [<-<->>-]    decrementing cell(0) and cell(1) by 48/0x30/'0' 
    <<      go to cell(0) 
    [      mulitplication loop 
     >     go to cell(1) 
     [>+>+<<-]   move cell(1) to cell(2) and cell(3) 
     >>     go to cell(3) 
     [<<+>>-]   move cell(3) back to cell(1) 
     <<<-    decrement cell(0) 
    ] 
    >[-]<     set cell(1) to 0 so that it can be used as counter 
    ++++[>++++[>+++<-]<-] adding 48/0x30/'0' to cell(2) 
    >>.      print result 

注意到,它仍然只的結果比10

0

一個真正偉大的資源是the Esolangs page on Brainfuck algorithms較小的正常工作。在那裏,乘法定義爲:

temp0[-] 
temp1[-] 
x[temp1+x-] 
temp1[ 
y[x+temp0+y-]temp0[y+temp0-] 
temp1-] 

因此,如果磁帶看起來一般般temp0 temp1 x y,用指針在temp0,然後將得到的替代將是:

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

然而,發生的主要問題當調用.輸出。您的方法僅適用於輸出單個數字的數字。到輸出單元格的內容爲多個時,可以使用以下代碼:

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

The original post containing this algorithm.