【问题标题】:How can I ensure a value is contained within an array?如何确保值包含在数组中?
【发布时间】:2010-12-02 19:59:13
【问题描述】:

以下是我的代码:

它用于测试一个质数生成器,该生成器创建并填充一个数组列表的前 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
    }
  }

有人可以帮我吗?

非常感谢。

【问题讨论】:

    标签: java arrays arraylist


    【解决方案1】:

    使用二分查找。你可以使用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");
    }
    

    【讨论】:

    • 我不需要知道 knownPrimes 中值的索引来执行此操作吗?
    • 不,您不需要知道相关键的索引。二进制搜索仅适用于已排序的元素列表。
    • 那么在我的情况下我将如何实现呢?抱歉,我不太明白。
    • @user476033 - Arrays.binarySearch 将搜索你给它的排序数组key。如果成功则返回值 >= 0,否则返回
    • 啊,我明白了,非常感谢,所以就我而言,我的代码将是: for (int index = 0; index = 0)); }
    【解决方案2】:

    正如Roman 所说,Arrays.binarySearch 可能是你最好的朋友。

    System.out.println(" looking up " + lookup + " -> " +
        ((Arrays.binarySearch(PRIMES, lookup) >= 0) ? "found" : "not found"));
    

    如果您的数组尚未排序,请先排序:

    Arrays.sort(PRIMES);
    System.out.println(" looking up " + lookup + " -> " +
        ((Arrays.binarySearch(PRIMES, lookup) >= 0) ? "found" : "not found"));
    

    如果你有Apache Commons Lang(或没有Arrays.binarySearch()的旧版Java,那么ArrayUtils.contains也是你的朋友:

    System.out.println(" looking up " + lookup + " -> " +
        ((ArrayUtils.contains(PRIMES, lookup)) ? "found" : "not found"));
    

    在这些 sn-ps 中,PRIMES 是一个包含要匹配的数字的 int[]lookup 是一个包含随机生成的质数的 int

    【讨论】:

    • 非常感谢。快速提问,当您问我的数组列表是否尚未排序时是什么意思?就像我排序的方式一样,我相信它应该先输入 2,然后是 3,然后是 5 .... 第 n 个素数。这会被认为是排序的吗?非常感谢您的回复:)
    • @user476033:在你的问题中,你说你想看看随机生成的素数是否在你的素数数组中,knownPrimes。在这种情况下,您已经按正确的顺序输入了值,从最小到最大。但是,如果您的情况并非如此(您的数组被打乱了),那么您需要先对数组进行排序(使值的顺序正确,从小到大)。这就是Arrays.sort() 的用武之地,因为它会对您的元素进行适当的排序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 2021-02-01
    • 2019-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多