我用MATLAB脚本语言写了一个简单的Brainfuck解释器,它可以执行随机bf程序(作为基因算法项目的一部分)。 我面临的问题是,在相当多的情况下,程序会出现无限循环,因此GA在那一点上被卡住了。
因此,我需要一种机制来检测无限循环并避免执行bf中的代码。
一个显而易见(琐碎)的情况是当我有:
[]
我可以检测并拒绝运行那个程序。
对于不平凡的情况,我发现基本思路是:确定循环一次如何改变当前单元格。如果变化为负数,那么最终会达到0,所以这是一个有限的循环。否则,如果变化是非负的,则是一个无限循环。
对于单个循环的情况,实现起来很容易,但是对于嵌套循环,它变得非常复杂。例如,(接下来的(1)指的是单元格1的内容等)
++++ Put 4 in 1st cell (1)
>+++ Put 3 in (2)
<[ While( (1) is non zero)
-- Decrease (1) by 2
>[ While( (2) is non zero)
- Decrement (2)
<+ Increment (1)
>]
(2) would be 0 at this point
+++ Increase (2) by 3 making (2) = 3
<] (1) was decreased by 2 and then increased by 3, so net effect is increment
因此代码不断运行。但是,对于在单元格1上执行的"+"和"-"的数量进行天真的检查会导致错误,因为"-"的数量更多,所以无法检测到无限循环。
有人能想出一种好的算法来检测无限循环吗?在bf中嵌套任意数量的循环。编辑:我知道一般情况下停机问题是无法解决的,但我不确定是否不存在特殊情况的例外。例如,Matlab可能作为超图灵机器能够确定bf程序的停机。我可能错了,但如果是这样,我想知道具体的原因和原因。
第二个编辑:我编写了一个据称为无限循环检测器的东西。它可能会忽略一些边缘情况(或者不太可能逃脱Turing先生的魔爪),但目前似乎对我还有效。用伪代码的形式,它如下:
subroutine bfexec(bfprogram)
begin
Looping through the bfprogram,
If(current character is '[')
Find the corresponding ']'
Store the code between the two brackets in, say, 'subprog'
Save the value of the current cell in oldval
Call bfexec recursively with subprog
Save the value of the current cell in newval
If(newval >= oldval)
Raise an 'infinite loop' error and exit
EndIf
/* Do other character's processings */
EndIf
EndLoop
end