最近遇到一个关于深奥编程语言的问题。有那种语言的工具。
> - increases the data pointer (so it points to the next cell in the array);
< - decreases the data pointer;
+ - increments the value in the current memory cell (i.e. one pointed by data pointer);
- - decrements the value in the current memory cell;
. - takes the value of current memory cell, converts it to character and prints to output;
, - takes one character from input and puts its ASCII code to the current memory cell.
[ - peeks at current cell, if the value here is non-zero, then simply proceeds to the next instruction, but if the value is 0, then searches forward for corresponding ] and sets code pointer immediately after this (i.e. skips the block within brackets);
] - moves code pointer back, to corresponding [.
: - takes the value of current memory cell and prints to output as a decimal integer;
; - takes next decimal integer (probably, consisting of several digits) from input and puts it to the current cell.
所以我必须用这种语言编写一个程序,输入 2 个数字 a 和 b 并将它们放入 cell0 和 cell1,然后输出这两个数字的总和。还有一个额外的要求(我遇到了麻烦)是在这个过程之后应该有 3 个单元格,cell0 保存 a,cell1 保存 b,cell 2 保存 a+b。
这是我的分析:我认为找到将总和放入 cell3 并打印它的方法很容易,只需;>;<[->>+]>[->+]>:
. 但是这样处理后,cell0 和 cell1 都将保持 0 而不是 a 和 b。所以我试图找到一种方法来使用上面的工具来实现这一点,我意识到给定工具,它就像一个电池,我只能将能量从一个电池转移到另一个电池,但我永远无法将能量从一个电池复制到另一个. 如果是这样,当我试图保留 cell0 和 cell1 时,我永远无法得到总和。
感谢我的问题下的@user3386109评论信息。我注意到有办法欺骗“能量平衡”。我们可以在循环中增加 2 个或更多单元格。所以我使用 5 个单元格并将第一个单元格和第二个单元格中的 a 和 b 转移到第 4 个和第 5 个单元格中,同时进行求和运算。所以我的算法会是这样的:
;>; input two numbers a and b
<[->>+>+] if the first cell is not zero then we keep decrementing it and incrementing the number in 3rd cell and 4th cell until it's zero.
>[->+>>+] if the second cell is not zero then we keep decrementing it and incrementing the number in 3rd cell and 5th cell until it's zero.
then we transfer back value a and b from 4th and 5th cell to 1st and 2nd cell
>>[-<<<+]>[-<<<+]
<<: go back 3rd cell and print out.
所以最后我的代码是:
;>;<[->>+>+]>[->+>>+]>>[-<<<+]>[-<<<+]<<:
但这是不对的,我检查了几次并找不到错误。有人帮我吗?谢谢!!!