以下是我的代码:
它用于测试素数生成器,该生成器创建并填充数组列表的前 n 个素数。在我的测试中,我创建了一个已知素数的数组,然后使用我的方法构建前 50 个 (knownPrimes.length) 素数的数组列表。然后选择一个随机数,我想断言使用我的方法 nextRandomPrime (从未知/生成的素数数组列表中选择一个数字)选择的每个素数都包含在数组knownPrimes中。我该如何做到这一点?
在伪代码中我想做的是:
assertTrue(createdPrimeList.nextRandomPrime is a value in the array knownPrimes);
这是我到目前为止所得到的:
public void comparePrimes() {
int[] knownPrimes = new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229 };
Primes createdPrimeList = new Primes (knownPrimes.length);
for (int index = 0; index < noOfTests; index++) //noOfTests is a global variable
{
assertTrue( createdPrimeList.nextRandomPrime( ) IS IN knownPrimes );//line I am struggling with
}
}
有人可以帮我吗?
非常感谢。
最佳答案
使用二分查找。您可以使用Arrays.binarySearch(int[] array, int key)
.
为了验证下一个值是否存储在 knownPrimes
中,您应该执行以下操作:
int nextValue = createdPrimeList.nextRandomPrime();
if (Arrays.binarySearch(knownPrimes, nextValue) >= 0) {
System.out.println("The value is already stored in known primes");
}
关于java - 如何确保数组中包含值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4339269/