Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method called findCommon that takes three arrays of positive integers as

ID: 3643945 • Letter: W

Question

Write a method called findCommon that takes three arrays of positive integers as parameters. The first two array parameters are filled with ints. Fill the third array parameter with all of the values that are common from the first two arrays and the rest of the array with zeros. No value should appear in the third array more than once. For example:



Array 1: 3 8 5 6 5 8 9 2

Array 2: 5 15 4 6 7 3 9 11 9 3 12 13 14 9 5 3 13



Array 3 should be set to: 3 5 6 9 0 0 0 0 (assuming it started with length = 8)

Explanation / Answer

public static void main(String[] args)
{
public static void findCommon(int[] input1, int[] input2, int[] output)
{
// sort the first array, makes it easier to have sorted output
java.util.Arrays.sort(input1);

int idx = 0;

// check for common elements
for(int i = 0; i < input1.length; i++)
{
// ignore duplicates
if(i > 1 && input1[i-1] == input1[i])
{
continue;
}

for(int j = 0; j < input2.length; j++)
{
if(input1[i] == input2[j])
{
output[idx++] = input1[i];
break;
}
}
}

// fill rest of output with zeroes
for(int i = idx; i < output.length; i++)
{
output[i] = 0;
}
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote