Nicole I.
Nicole I.

Reputation: 95

Comparing Two Arrays & Get the Percent that Match - Java

Background: Very new at Java, have little understanding. Would prefer a "point in the right direction" with explanation, if possible, than a copy/paste answer without explanation. If I want to stop being a novice, I need to learn! :)

Anyway, my goal is, as simply as possible, to be given 2 arrays numberList and winningNumbers, compare them, and return the percentage that numberList matches winningNumbers. Both array lengths will always be 10.

I have no idea where to start. I have been googling and going at this for 2 hours. My idea is to write a for loop that compares each individually integer in a string to one in the other, but I am not sure how to do that, or if there is a simpler method. I have little knowledge of arrays, and the more I google the more confused I become.

So far the only thing I have is

public double getPercentThatMatch(int[] winningNumbers) {}

numberList is preset.

Upvotes: 1

Views: 4781

Answers (8)

VICTOR MARTINS
VICTOR MARTINS

Reputation: 21

//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;

Upvotes: 0

Laszlo Lugosi
Laszlo Lugosi

Reputation: 3829

You should use List over array, because that's a convenient way, but with array:

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;
}

}

Hope this helps. ;)

Upvotes: 0

vinay chilakamarri
vinay chilakamarri

Reputation: 251

In my approach I tried storing the winning numbers in a Hashset (one pass iteration, O(n) )

And when iterating on the numberList, I would check for presence of number in Hashset and if so, I will increment the counter. (one pass iteration, so O(n) )

The percentage is thus calculated by dividing the counter with size of array.

See if the sample code makes sense:

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);
    }
}

Upvotes: 0

Zaffaro
Zaffaro

Reputation: 131

Since you wanted to be pointed in the right direction, rather than havving proper code, and assuming you want to use arrays to solve the problem, try to put something like this in your method:

(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

So for every index in one array, you check against every other index of the other array. Increase a counter each time there's a match, and you'll be able to get a ratio of matches. If you use an integer as a counter, remember that division with integers acts funky, so you'd need to throw to a double:

double aDoubleNumber = (double) intNumber / anotherIntNumber

Upvotes: 1

gknicker
gknicker

Reputation: 5569

Here's a runnable example of how you would compare the two arrays of ints to get a percent match.

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 + "%");
    }
}

Output:

80%

Upvotes: 1

msleevi
msleevi

Reputation: 124

I am going to attempt to beat a dead horse and explain the easiest (conceptual) way to approach this problem I will include some code but leave a lot up to interpretation.

You have two arrays so I would change the overall method to something like this:

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*/
} 

You are going to move through the first array with the first loop and the second array with the second loop. So you go through every value in arrayB for each value in arrayA to check.

Upvotes: 0

Razib
Razib

Reputation: 11173

The problem would be easier if we consider them set. Let you have two set -

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

Now make a copy of s1 for example s11 and do the following thing -

s1.retainAll(s2);  

Now s1 contains only element of both sets - that is the intersection.

After that you can easily calculate the percentage

Edit: You can convert the array to a set easily by using the following code snippet (I am assuming you have array of int) -

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

I think this trick will works for other primitive type also.

Hope this will help.
Thanks a lot.

Upvotes: 0

Calum
Calum

Reputation: 2130

one way you could approach it is to:

1) convert both lists to sets.

2) subtract one from the other. ie if 4 are the same, the resulting set will have the 6 values not the same

3) 10 - (size of resulting set) * 100 = %

Upvotes: 1

Related Questions