gpt4 book ai didi

java - junit-quickcheck - 生成保持深度有限的随机树

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:15:26 25 4
gpt4 key购买 nike

我正在练习 junit-quickcheck。

我已经为二叉树的三个排序组件(NodeLeafEmpty)准备了生成器。

我希望创建随机树并验证它们的属性。

Node 的生成器根据特定概率为其两个分支选择更多生成器。

但是,我希望树木在每次运行期间的某个时间停止生长。构建作为 Node 的子树的概率必须随着世代的演进而降低。

我希望能够通过使用 GenerationStatus 来控制树的深度,但我看不出具体如何。

另一种假设是在 generate() 之前调用下一个生成器的方法 configure(),但我还没有成功。

实现这一切的正确方法是什么?

最佳答案

您可以使用 GenerationStatus#setValue(Key, Object)在生成器之间传递值。

这是我编写的一个示例,它生成严格递减的正整数列表:

import com.pholser.junit.quickcheck.generator.GenerationStatus;
import com.pholser.junit.quickcheck.generator.Generator;
import com.pholser.junit.quickcheck.random.SourceOfRandomness;

import java.util.ArrayList;
import java.util.List;

public class ListGenerator extends Generator<List<Integer>> {

private static final int MAX_VALUE = 100;
private static final GenerationStatus.Key<Integer> PREVIOUS_KEY = new GenerationStatus.Key<>("previous", Integer.class);

@SuppressWarnings("unchecked")
public ListGenerator() {
super((Class<List<Integer>>) (Class) List.class);
}

public List<Integer> generate(SourceOfRandomness sourceOfRandomness, GenerationStatus generationStatus) {
List<Integer> result = new ArrayList<>();

int previous = generationStatus.valueOf(PREVIOUS_KEY).orElse(MAX_VALUE);
int current = sourceOfRandomness.nextInt(previous);

if (current > 0) {
result.add(current);

generationStatus.setValue(PREVIOUS_KEY, current);
Generator<List<Integer>> listGen = gen().make(ListGenerator.class);
result.addAll(listGen.generate(sourceOfRandomness, generationStatus));
generationStatus.setValue(PREVIOUS_KEY, null);
}

return result;
}
}

关于java - junit-quickcheck - 生成保持深度有限的随机树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36454149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com