Compare all elements between arrays and return all possible matches

问题: I'm trying to create a function that compares all elements of an array with all elements of a second array and will return all possible matches, and message if no matches a...

问题:

I'm trying to create a function that compares all elements of an array with all elements of a second array and will return all possible matches, and message if no matches are found. When I try to implement the code, I get an index out of bound error. The inner for loop probably maxed out before the outer for loop can finish running. How do I modify it to prevent such a scenario from occurring?

Stocks[] stockList3 = new Stocks[3];
stockList3[0] = new Stocks("a", 2, 1, "Buy");
stockList3[1] = new Stocks("a", 3, 1, "Buy");
stockList3[2] = new Stocks("a", 4, 1, "Buy");

Stocks[] stockList4 = new Stocks[3];
stockList4[0] = new Stocks("a", 2, 1, "Buy");
stockList4[1] = new Stocks("a", 5, 1, "Buy");
stockList4[2] = new Stocks("a", 4, 1, "Buy");

public void matching(Stocks[] array1, Stocks[] array2) {
    for (int i = 0; i < array1.length; i++) {
        for (int j = 0; i < array2.length; j++) {
            if (array1[i].stockPrice == array2[j].stockPrice) {
                System.out.println("It's a match at $" + array1[i].stockPrice);
            }
            System.out.println("still searching...");
        }
        System.out.println("first loop test...");
    }
}

回答1:

What about instead of two for loops, use Set collection to store existed stockPrices for one of an array?

public static List<Stocks> matching(Stocks[] one, Stocks[] two) {
    Set<Integer> stockPrices = Arrays.stream(one)
                                     .map(stock -> stock.stockPrice)
                                     .collect(Collectors.toSet());
    return Arrays.stream(two)
                 .filter(stock -> stockPrices.contains(stock.stockPrice))
                 .collect(Collectors.toList());
}

It use O(n) additional memory (where n is one.length) with O(n + m) performance time (where m is two.length).


回答2:

In your j-loop you were saying i<array2.length instead of j<array2.length

public void matching ( Stocks[] array1, Stocks[] array2){
    for (int i=0; i<array1.length;i++){

        for (int j=0;
                 j<array2.length;  //this j was an i
                 j++){

            if (array1[i].stockPrice == array2[j].stockPrice){
                System.out.println("It's a match at $" + array1[i].stockPrice);



            }
            System.out.println("still searching...");
        }
        System.out.println("first loop test...");   
    }

}
  • 发表于 2019-03-12 01:08
  • 阅读 ( 143 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除