比较两个数组并获得匹配的百分比 - Java

Comparing Two Arrays & Get the Percent that Match - Java

背景:在Java很新,了解不多。如果可能的话,宁愿 "point in the right direction" 有解释,也不愿 copy/paste 没有解释的回答。如果我想不再是新手,我需要学习! :)

无论如何,我的目标是尽可能简单地给出 2 个数组 numberList 和 winningNumbers,比较它们,然后 returnnumberList 与 winningNumbers 匹配的百分比。两个数组长度将始终为 10。

我不知道从哪里开始。我已经在谷歌上搜索了 2 个小时。我的想法是编写一个 for 循环,将字符串中的每个整数与另一个整数进行比较,但我不确定该怎么做,或者是否有更简单的方法。对数组一窍不通,越google越糊涂

到目前为止我唯一拥有的是

public double getPercentThatMatch(int[] winningNumbers) {}

numberList 已预设。

您可以采取的一种方法是:

1) 将两个列表都转换为集合。

2) 一个减去另一个。即如果 4 个相同,则结果集将有 6 个值不相同

3) 10 - (结果集的大小) * 100 = %

既然你想被指向正确的方向,而不是拥有正确的代码,并且假设你想使用数组来解决问题,请尝试在你的方法中加入这样的东西:

(loop through arrayA){
  (loop through arrayB){
    if (current arrayA number is equal to current arrayB number){
        then increase match counter by one, since this exists.
        also break out of current arrayB loop. (Check next arrayA now.)
    }
  }
}
When done: return 100*matchCount/totalCount, as a double

因此,对于一个数组中的每个索引,您都要检查另一个数组的每个其他索引。每有一场比赛就增加一个计数器,你就能得到比赛的比例。如果您使用整数作为计数器,请记住用整数除法很时髦,因此您需要抛出一个双精度值:

double aDoubleNumber = (double) intNumber / anotherIntNumber

如果我们考虑它们的集合,问题会更容易。让你拥有两套-

Set<Integer> s1 = //a HashSet of Integer;
Set<Integer> s2 = //a HashSet of Integer;

现在复制 s1 例如 s11 并执行以下操作 -

s1.retainAll(s2);  

现在 s1 只包含两个集合的元素 - 即交集。

之后你可以很容易地计算出百分比

编辑: 您可以使用以下代码片段轻松地将数组转换为集合(我假设您有 int 数组)-

Set<Integer> s1 = new HashSet<Integer>(Arrays.asList(somePrimiteiveIntArray)); 

我认为这个技巧也适用于其他基本类型。

希望这会有所帮助。
非常感谢。

我将尝试打破僵局并解释解决此问题的最简单(概念)方法我将包含一些代码,但还有很多内容需要解释。

你有两个数组,所以我会把整个方法改成这样:

public double getPercentage(int[] arrayA, int[] arrayB) {
  double percentage=0;
  for(/*go through the first array*/) {
    for(/*go through second array*/) {
      if(arrayA[i]==arrayB[j]) { /*note the different indices*/
        percentage++; /*count how many times you have matching values*/
        /* NOTE: This only works if you don't have repeating values in arrayA*/
      }
    }
  }
  return (percentage/arrayA.length)*100; /*return the amount of times over the length times 100*/
} 

您将通过第一个循环遍历第一个数组,通过第二个循环遍历第二个数组。因此,您遍历 arrayB 中的每个值以检查 arrayA 中的每个值。

这是一个可运行的示例,说明如何比较 int 的两个数组以获得匹配百分比。

public class LotteryTicket {
    int[] numberList;

    LotteryTicket(int... numbers) {
        numberList = numbers;
    }

    public int getPercentThatMatch(int[] winningNumbers) {
        Arrays.sort(numberList);
        Arrays.sort(winningNumbers);
        int i = 0, n = 0, match = 0;
        while (i < numberList.length && n < winningNumbers.length) {
            if (numberList[i] < winningNumbers[n]) {
                i++;
            } else if (numberList[i] > winningNumbers[n]) {
                n++;
            } else {
                match++;
                i++;
                n++;
            }
        }
        return match * 100 / winningNumbers.length;
    }

    public static void main(String[] args)
    {
        int[] winningNumbers = { 12, 10, 4, 3, 2, 5, 6, 7, 9, 1 };
        LotteryTicket ticket = new LotteryTicket(5, 2, 6, 7, 8, 4, 3, 1, 9, 0);
        int percentMatching = ticket.getPercentThatMatch(winningNumbers);
        System.out.println(percentMatching + "%");
    }
}

输出:

80%

在我的方法中,我尝试将中奖号码存储在哈希集中(一次迭代,O(n))

并且在迭代 numberList 时,我将检查 Hashset 中是否存在数字,如果是,我将递增计数器。 (一次迭代,所以 O(n) )

因此,百分比是通过将计数器除以数组大小来计算的。

看看示例代码是否有意义:

import java.util.HashSet;

public class Arraycomparison {

    public static void main(String ... args){

        int[] arr0 = {1,4,2,7,6,3,5,0,3,9,3,5,7};
        int[] arr1 = {5,2,4,1,3,7,8,3,2,6,4,4,1};
        HashSet set = new HashSet();

        for(int j = 0; j < arr1.length; j++){
            set.add(arr1[j]);
        }

        double counter = 0;
        for(int i = 0; i < arr0.length; i++){
            if(set.contains(arr0[i])){
                counter++;
            }
        }

        System.out.println("Match percentage between arrays : " + counter/arr0.length*100);
    }
}

您应该使用 List 而不是数组,因为这是一种方便的方法,但是对于数组:

public class Winner {
public static void main(String... args) {
    double result = getPercentThatMatch(new int[]{1,2,3,4,5}, new int[]{2,3,4,5,6});
    System.out.println("Result="+result+"%");
}

public static double getPercentThatMatch(int[] winningNumbers,
        int[] numberList) { // it is confusing to call an array as List
    int match = 0;
    for (int win : winningNumbers) {
        for (int my : numberList ){
            if (win == my){
                System.out.println(win + " == " + my);
                match++;
            }
        }
    }
    int max = winningNumbers.length; // assume that same length
    System.out.println("max:"+max);
    System.out.println("match:"+match);
    double devide = match / max; // it won't be good, because the result will be intm so Java will trunc it!
    System.out.println("int value:"+devide);
    devide = (double) match / max; // you need to cast to float or double
    System.out.println("float value:"+devide);

    double percent = devide * 100; 
    return percent;
}

}

希望这对您有所帮助。 ;)

//For unique elements
getpercentage(arr1, arr2){
      res = arr1.filter(element=>arr2.includes(element))
   return res.lenght/arr2.lenght * 100;
 }

//For duplicate elements
getpercentage(arr1, arr2){
   const setA = Set(arr1);
   const setB = Set(arr2);
   Let res = [ ];
   for(let i of setB){
         if(setA.has(i)){
               res.push(i);
         }
  }
  return res.lenght/setA.size* 100;