Ask Question
4 November, 04:44

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.

+1
Answers (1)
  1. 4 November, 07:49
    0
    According to the complete question, the code below gives the solution to the problem in Java with appropriate comments

    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 ("/nFirst Array: ");

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

    {

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

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

    }

    System. out. print ("/n/nSecond Array: ");

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

    {

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

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

    }

    System. out. println ("/n");

    /*

    * 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 ("/n");

    }

    }
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “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 ...” in 📙 Engineering if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers