Question
I have this code, which finds the common values of 3 arrays. I need code that will find the common elements of an input of
I have this code, which finds the common values of 3 arrays. I need code that will find the common elements of an input of n number arrays. I believe a recursive code would work best, but I cannot figure one out.
// This function prints common elements in ar1
void findCommon(int ar1[], int ar2[], int ar3[])
{
// Initialize starting indexes for ar1[], ar2[] and ar3[]
int i = 0, j = 0, k = 0;
// Iterate through three arrays while all arrays have elements
while (i < ar1.length && j < ar2.length && k < ar3.length)
{
// If x = y and y = z, print any of them and move ahead
// in all arrays
if (ar1[i] == ar2[j] && ar2[j] == ar3[k])
{ System.out.print(ar1[i]+" "); i++; j++; k++; }
// x < y
else if (ar1[i] < ar2[j])
i++;
// y < z
else if (ar2[j] < ar3[k])
j++;
// We reach here when x > y and z < y, i.e., z is smallest
else
k++;
}
}
I need to know how to change the code so I can compare n number of arrays at a time. Or if theres and entirely different code to do what I want.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started