问题描述
我正在尝试证明以下 RandomSeach-Algorithm 并找出循环的不变量。
由于函数 randomIndex(..)
创建了一个随机数,所以我不能使用像
? ≥ 0 ∧ ? < ? − 1 ⇒ ?[?] ≠ ????e
。这意味着,0 到 i-1 之间的所有元素,其中 i 是当前检查元素的索引,不是搜索元素。
所以我想我定义了一个假设序列 r
,其中包含已经与搜索值比较或将要与搜索值比较的所有元素。这就是为什么它只是一个假设的序列,因为我实际上不知道将要与搜索值进行比较的元素,直到它们真正进行比较为止。
这意味着它适用于 r.lenght() ≤ runs
并且在找到搜索元素的情况下
(r[r.lenght()-1] = value) ↔ (r[currentRun] = value).
然后我可以定义一个不变量,如:
? ≥ 0 ∧ ? < currentRun ⇒ r[?] ≠ ????e
我可以这样做吗,因为序列 r 不是真实的?感觉不对。有人对不变量有不同的想法吗?
程序:
public boolean RandomSearch (int value,int[] f,int runs) {
int currentRun = 0;
boolean found = false;
while (currentRun < runs || !found) {
int x = randomIndex(0,n-1)
if (value == f[x]) {
found = true;
}
currentRun = currentRun + 1;
}//end while
return found;
}//end RandomSearch
解决方法
好的,
我使用以下不变量
inlineformset_factory
我可以证明算法:)