【问题标题】:Comparing Two Arrays & Get the Percent that Match - Java比较两个数组并获得匹配的百分比 - Java
【发布时间】:2015-03-05 22:40:56
【问题描述】:

背景:Java 新手,了解不多。如果可能的话,宁愿“指向正确的方向”有解释,也不愿复制/粘贴没有解释的答案。如果我不想成为新手,我需要学习! :)

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

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

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

public double getPercentThatMatch(int[] winningNumbers) {}

numberList 是预设的。

【问题讨论】:

  • 遍历一个数组,并为每个元素检查它是否在另一个数组中。如果是,加 10%。
  • 顺序重要吗?如果没有,它们是否已排序? (想想这会如何影响你未来的解决方案)我建议你简单地使用数组。循环,打印。试试语法。
  • 你写过嵌套循环的代码吗?
  • 两个问题,数字的位置重要吗?一个列表可以有两个数字吗?
  • @Calum 不,没关系,不,它不能。

标签: java arrays compare


【解决方案1】:

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

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

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

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

【讨论】:

  • 听起来不错,但如果两个相同的数字出现在不同的地方怎么办?
  • @NicoleI。集合的好处在于它们有一种方法可以让您查看集合是否包含数字。不管它的位置在哪里。但我个人认为,如果你是 java 新手,其他数据类型不应该使用。
【解决方案2】:

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

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%

【讨论】:

    【解决方案3】:

    由于您希望指向正确的方向,而不是拥有正确的代码,并且假设您想使用数组来解决问题,因此请尝试在您的方法中添加这样的内容:

    (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
    

    【讨论】:

    • 如果数字不是完全相同的索引怎么办?您需要嵌套 for 循环并使用 arrayA[index1] 检查每个 arrayB[index2]。
    • 是的,我首先认为任务是数字在同一个索引处。现在添加了嵌套循环。
    【解决方案4】:

    如果我们认为它们已设置,问题会更容易。让你有两套——

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

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

    s1.retainAll(s2);  
    

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

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

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

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

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

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

    【讨论】:

    • 当有重复号码时,这将不起作用。 (只是说...)
    【解决方案5】:

    我将尝试打败一匹死马并解释解决这个问题的最简单(概念)方法我将包含一些代码,但还有很多内容需要解释。

    你有两个数组,所以我会将整体方法更改为这样的:

    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 中的每个值。

    【讨论】:

      【解决方案6】:

      在我的方法中,我尝试将中奖号码存储在 Hashset 中(一次迭代,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);
          }
      }
      

      【讨论】:

        【解决方案7】:

        你应该使用 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;
        }
        

        }

        希望这会有所帮助。 ;)

        【讨论】:

          【解决方案8】:
          //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;
          

          【讨论】:

            猜你喜欢
            • 2019-10-30
            • 1970-01-01
            • 2018-04-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-09-04
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多