Reputation:
I need to make 2 arrays called A and B, both of type int with size 100. Each index should be a random number between 0 and 100 inclusive and then compare both arrays, and say how many times 2 of the same number appeared in both arrays.
This is what I have so far
int count = 0;
int [] A = new int [100];
int [] B = new int [100];
for(int i = 0; i < A.length; i++){
A [i] = (int)(Math.random()*101);
System.out.println("Array A: " + i);
}
for(int i = 0; i < B.length; i++){
B [i] = (int)(Math.random()*101);
System.out.println("Array B: " + i);
}
if(A [i] == B [i]){
count++;
}
I'm not sure how to show how many times 2 of the same number appeared in both arrays.
Upvotes: 0
Views: 103
Reputation: 104
You started off nicely, but you need a nested for-loop to check each of the indexes.
ALSO-- make sure that in your arrays you print out A[i] and B[i] otherwise you're just printing out the number of the index as opposed to the number inside the index.
int count = 0;
int[] A = new int[100];
int[] B = new int[100];
//Create the first array
for (int i = 0; i < A.length; i++) {
A[i] = (int)(Math.random() * 101);
System.out.println("Array A: " + A[i]);
}
//Create the second array
for (int i = 0; i < B.length; i++) {
B[i] = (int)(Math.random() * 101);
System.out.println("Array B: " + B[i]);
}
//Check the indexes and make sure they are all compared-- 10,000 comparisons are made
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
if(A[i] == B[j])
count++;
}
}
Hopefully that posted correctly... first time posting code on this website, but I hope that I was of help!
Keep in mind if the same number is being posted twice, you're going to get counts over 100.
Good luck!
Upvotes: 0
Reputation: 53829
Alternatively, if you don't need the 2 arrays, you can simply do:
int count = Random.ints(100, 0, 101).boxed().collect(toSet())
.retainAll(Random.ints(100, 0, 101).boxed().collect(toSet()))
.size();
Upvotes: 1
Reputation: 17132
You need to loop through both of the arrays:
int count = 0;
int [] A = new int [100];
int [] B = new int [100];
for(int i = 0; i < A.length; i++){
A [i] = (int)(Math.random()*101);
System.out.println("Array A: " + i);
}
for(int i = 0; i < B.length; i++){
B [i] = (int)(Math.random()*101);
System.out.println("Array B: " + i);
}
// Loop through the first array
for(int i = 0; i < A.length; i++) {
// For each element in the first array, loop through the whole second one
for (int j = 0; j < B.length; j++) {
// If it's a match
if(A[i] == B[j])
count++;
}
}
System.out.println("Count: " + count);
Upvotes: 1