35.4k views
1 vote
The numbers should be added to the merged array in an alternating pattern: first from list 1, then from list 2, then list 1 again, etc. If a number in one of the arrays already appears in the merged array, then it should be ignored, and the program should alternate to the other list again. For example, if the first list begins 1 2 3 10, and the second begins 3 4 5 8, then the merged list would begin 1 3 2 4 5 10 8.

User Hvester
by
8.4k points

1 Answer

2 votes

Answer:

According to the complete question, the code below gives the solution to the problem in Java with appropriate comments

Step-by-step explanation:

import java.util.Scanner;

import java.lang.Math;

class Main {

public static void main(String[] args) {

int length = 0;

boolean lengthCheck = true;

Scanner scan = new Scanner(System.in);

while (lengthCheck == true)

{

System.out.println("Enter an array length (must be 10 or greater):");

length = scan.nextInt();

if (length >= 10)

{

lengthCheck = false;

}

}

int[] firstArray = new int[length];

int[] secondArray = new int[length];

System.out.print("\\First Array: ");

for (int i = 0; i < length; i++)

{

firstArray[i] = (int) (Math.random() * 100) + 1;

System.out.print(firstArray[i] + " ");

}

System.out.print("\\\\Second Array: ");

for (int i = 0; i < length; i++)

{

secondArray[i] = (int) (Math.random() * 100) + 1;

System.out.print(secondArray[i] + " ");

}

System.out.println("\\");

/*

* A boolean array of length 100 to track list of number we have already added to merge list

*/

boolean[] isAdded = new boolean[100];

int[] merge = new int[(firstArray.length + secondArray.length)];

int j=0;

for (int i = 0; i < length; i++)

{

if(!isAdded[firstArray[i] - 1]) {

merge[j] = firstArray[i];

j++;

isAdded[firstArray[i] - 1] = true;

}

if(!isAdded[secondArray[i] - 1]) {

merge[j] = secondArray[i];

j++;

isAdded[secondArray[i] - 1] = true;

}

}

System.out.print("Merged Array: ");

for (int i = 0; i < 2*length && merge[i] != 0; i++)

{

System.out.print(merge[i] + " ");

}

System.out.println("\\");

}

}

User Lunicon
by
8.4k points