Aker
Aker

Reputation: 59

Java int array find and print matching

Here I have a Java case switch where I compare 2 randomly generated 7 number integer arrays, lottery1 array is generated earlier depending on the user input. The problem I am having is, I need to compare the two arrays and count the number of matching numbers and then print the matching numbers and how many numbers were the same.

I'm trying to put the matching numbers into the array called similar, now it's just comparing the first number of lottery1 to all of the lottery2's numbers. There's plenty of tutorials on how to compare arrays that return a bool but I need the matching numbers, please help!

public class Main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        Random rnd = new Random();

        int[] lottery1 = new int[7];
        for (int i = 0; i < lottery1.length; i++) {
            lottery1[i] = rnd.nextInt(52);
        }
        Arrays.sort(lottery1);
        System.out.printf("Lottery array is: %s", Arrays.toString(lottery1));

        System.out.print("\nDo you want to generate an array(y/n): ");
        char answer = scan.next().charAt(0);
        switch (answer) {
            case 'n' -> System.out.print("Goodbye!");
            case 'y' -> {
                int[] lottery2 = new int[7];
                for (int i = 0; i < lottery2.length; i++) {
                    int rndNum = rnd.nextInt(52);
                    lottery2[i] = rndNum; //Here i fill the lottery2 with random 
                }                                                         numbers
                Arrays.sort(lottery2);
                System.out.printf("Program created an array of: %s", Arrays.toString(lottery2));
                
                int j = 0;
                int[] similar = new int[7]; //I'm trying to put the matching numbers into this new array
                for (int i = 0; i < 7; i++)
                {
                    if (lottery2[i] == lottery1[j])
                    {
                        lottery1[i] = similar[j];
                        i++;
                        j++;
                    }
                }
                System.out.printf("\nThis is how many numbers are matching: ");
                System.out.printf("\nThese numbers are matching ones: ");
            }

Upvotes: 1

Views: 1280

Answers (3)

Nowhere Man
Nowhere Man

Reputation: 19545

This seems to be a good task to learn decomposition of the bigger tasks into subtasks.

The first subtask is definitely to generate an array of size K of random integer values in the given range, let's assume that for lottery the range is from 1 to N inclusive.

Then two arrays are generated, and the second subtask is to find a match between these two.

An example implementation using Stream API could be as follows:

  1. Generate array of random integers:
static int[] getRandomArray() {
    return getRandomArray(7, 52);
}

static int[] getRandomArray(int k, int n) {
    int[] result = new SecureRandom().ints(1, n + 1) // n + 1 to ensure N can be included
                                     .distinct() // make sure all elements are different
                                     .limit(k)   // pick K numbers
                                     // .sorted() // sort the array if needed
                                     .toArray();
    System.out.println("Random array: " + Arrays.toString(result));
    return result;
}
  1. Match the results with the help of Set:
static int[] findMatch(int[] lotteryPick, int[] lotteryGuess) {
    Set<Integer> set = Arrays.stream(lotteryPick).boxed().collect(Collectors.toSet());
    int[] match = Arrays.stream(lotteryGuess).filter(x -> set.contains(x)).toArray();

    if (match.length == 0) {
        System.out.println("No matched numbers found");
    } else {
        String num = match.length == 1 ? " number" : " numbers";
        System.out.println("Matched: " + match.length + num + ", the match: " + Arrays.toString(match));
    }
    System.out.println("-------------------------------");

    return match;
}

Then the tests would look as simple as:

int t = 5;
while (t--> 0) {
    findMatch(getRandomArray(), getRandomArray());
}

Possible output:

Random array: [26, 33, 29, 23, 49, 1, 14]
Random array: [37, 3, 27, 29, 34, 24, 36]
Matched: 1 number, the match: [29]
-------------------------------
Random array: [9, 4, 32, 27, 29, 18, 35]
Random array: [34, 2, 23, 29, 27, 6, 30]
Matched: 2 numbers, the match: [29, 27]
-------------------------------
Random array: [35, 18, 4, 42, 19, 6, 13]
Random array: [30, 8, 4, 37, 31, 9, 46]
Matched: 1 number, the match: [4]
-------------------------------
Random array: [52, 7, 47, 22, 12, 9, 26]
Random array: [46, 13, 20, 17, 1, 4, 34]
No matched numbers found
-------------------------------
Random array: [31, 40, 9, 3, 2, 49, 44]
Random array: [2, 15, 13, 36, 10, 43, 12]
Matched: 1 number, the match: [2]
-------------------------------

Upvotes: 2

rzwitserloot
rzwitserloot

Reputation: 102903

int[] similar = new int[7]; //I'm trying to put the matching numbers into this new array

lottery1[i] = similar[j];

similar is an array of size 7, filled with seven 0 values (because arrays start out zeroed out). You never write anything into similar. You overwrite lottery1 with what's in similar. In other words, this code is an obtuse way to accomplish:

lottery1[i] = 0;

which surely isn't what you wanted. You also initialize similar to have size 7 but this is incorrect: Who knows how many similar numbers even exist?

You have 4 options:

  1. Use a List<Integer> list = new ArrayList<Integer>(); - unlike arrays, arraylists don't need to be pre-sized, you can just call list.add(), and the list will take care of it. It's variable size.

  2. Loop twice; once to determine how many matches, then you can make your similar array with the right size, and then a second time to fill it.

  3. Make the similar array at 7, also count how many similar numbers exist, then when done copy the data over to a new array at the proper size.

  4. Make the similar array at size 7 and use a special sentinel value (such as -1) to indicate that this one should not be shown/printed.

Also, your code is buggy: If you have replications, you overcount. Imagine lottery1 is [1,2,3,4,5,6,1] and lottery2 is [1,2,2,3,4,1,6], your algorithm would say that there are 6 matches, which doesn't sound right (the first '1' matches twice, the second '1' matches twice, and the 2 matches 2. You're going to have to think about how you want to tackle this issue.

Think about this, and write down some sample inputs + the sample output you desire, and then think about how to write code that does this. Don't just dive in.

Upvotes: 2

Daniel
Daniel

Reputation: 113

I get that you are trying to compare all numbers in 2 list and get the ones with same values I wrote this code I think it answers your question:

    int[] matching = new int[7];
    int[] lottery1 = new int[7];
    int[] lottery2 = new int[7];

    // Generate random numbers
    for (int i = 0; i < 7; i++) {
        lottery1[i] = (int) (Math.random() * 52.0);
        lottery2[i] = (int) (Math.random() * 52.0);
    }

    // Compare and store matching numbers in matching array;
    // The nested loop below will compare the every element of the both lists
    // together and store the
    // results in matching array
    int matchingCount = 0;
    for (int i = 0; i < 7; i++) {
        for (int j = 0; j < 7; j++) {
            if (lottery1[i] == lottery2[j]) {
                matching[matchingCount++] = lottery1[i];
            }
        }
    }

    System.out.print("Matching Count: " + matchingCount + "\nMatch Numbers: [ ");
    for (int i = 0; i < matchingCount; i++)
        System.out.print(matching[i] + " ");
    System.out.println("]");

Upvotes: 2

Related Questions