Question

In: Computer Science

I'm trying to get the union of two arrays and I tried making a loop that...

I'm trying to get the union of two arrays and I tried making a loop that does so. I tried also making the loop give me the size of the array as well from the union of the two arrays. Please check my loop to see what is wrong with it because it is not doing what I want it to do. I'm also not sure how to get the correct size of the array after the two arrays have been stored inside the union array.

Arrays:

a[] = {5, 10, 15, 20, 25, 30, 35, 40};

b[] = {3, 10, 13, 20, 23, 28, 30, 33, 35};

What I should be getting:

union[] = {3,5,10,13,15,20,23,25,28,30,33,35,40};

My loop that I made:

void Union(int left[], int left_size, int right[], int right_size, int result[], int& result_size)
{
    int* walker1;
    int* walker2;
    int* walker3;
    int counter = 0;
 
    walker1 = left;                                              //first pointer points to left array
    walker2 = right;                                            //second pointer points to right array
    walker3 = result;                                           //third array points to the appended result array
 
    while(counter < left_size || counter < right_size)
    {
        if(*walker1 == *walker2)                           //checks if the elements are the same number
        {
            *walker3 = *walker1;                            //pointer walker3 takes in element of walker1
            walker1++;                                          //if the numbers are the same, walker1
            walker2++;                                          //and walker2 increments to the next element to compare
            walker3++;
        }
        else if(*walker1 < *walker2)                      //checks if element in first array is less than the second array
        {
            *walker3 = *walker1;                            //walker3 takes in element of walker1
            walker1++;                                          //walker1 will increment to the next element to compare to the second array
            walker3++;
        }
        else if(*walker1 > *walker2)
        {
            *walker3 = *walker2;
            walker2++;
            walker3++;
        }
        counter++;
    }
 
    while(counter < right_size)
    {
        *walker3 = *walker2;
        walker2++;
        walker3++;
        counter++;
    }
    result_size = counter;
    cout << result_size;
}
 
void test_Union()
{
    int* walker;
    int a[] = {5, 10, 15, 20, 25, 30};
    int b[] = {3, 10, 13, 20, 23, 28, 30, 33, 35};
    int resultSize;
    int unionArr[0];
 
    walker = unionArr;
    Union(a, LEFT_SIZE, b, RIGHT_SIZE, unionArr, resultSize);
    for(int i = 0; i < resultSize; i++)
    {
        cout << *walker << " ";
        walker++;
    }
 
    cout << endl << endl << endl;
}

Solutions

Expert Solution

Screenshot

Program

//Header files
#include <iostream>
using namespace std;
//Function to union left and right sorted array
void Union(int left[], int left_size, int right[], int right_size, int *result, int& result_size){
   int i = 0, j = 0;
   while (i < left_size && j < right_size)
   {
       //Check left array element less than right array element
       if (left[i] < right[j]) {
           result[result_size++] = left[i++];
       }
       //Check right array element less than left array element
       else if (right[j] < left[i]) {
           result[result_size++] = right[j++];
       }
       //Equal condition
       else{
           result[result_size++]=right[j++];
           i++;
       }
   }
   //Add remaining elements
   while (i < left_size) {
       result[result_size++] = left[i++];
   }
   while (j < right_size) {
       result[result_size++] = right[j++];
   }  
}
//Test function
void test_Union(){
   //For union array
   int* unionArray;
   //Size
   int resultSize = 0;
   //Test arrays
   int a[] = { 5, 10, 15, 20, 25, 30,35,40 };
   int b[] = { 3, 10, 13, 20, 23, 28, 30, 33, 35 };
   //Allocate max size needed for result array
   unionArray = new int[(sizeof(a) / sizeof(a[0]))+ (sizeof(b) / sizeof(b[0]))];
   //Call function
   Union(a,(sizeof(a) / sizeof(a[0])), b, (sizeof(b) / sizeof(b[0])), unionArray, resultSize);
   //Display union array
   for (int i = 0; i < resultSize; i++){
       cout << unionArray[i] << " ";
   }
   cout << endl << endl << endl;
}
//Main method
int main() {
   test_Union();
}

--------------------------------------------------------------------

Output

3 5 10 13 15 20 23 25 28 30 33 35 40

------------------------------------------------------------------

Note:-

I changed your function to generate union array in easiest way,I assume it's okay for you.


Related Solutions

I'm having trouble with my do while loop. I'm trying to get it where if the...
I'm having trouble with my do while loop. I'm trying to get it where if the user enter's 3 after whatever amount of caffeinated beverages they've entered before then the loop will close and the rest of my code would proceed to execute and calculate the average price of all the caffeinated beverages entered. Can someone please help me with this? Here's my Code: import java.util.Scanner; public class Main { public static void main(String[] args) { CaffeinatedBeverage[] inventory = new...
I'm trying to get my code to loop back to let the user input multiple patients....
I'm trying to get my code to loop back to let the user input multiple patients. import java.util.Scanner; public class XYZ {    public static void main(String[] args) {           String response;        do{            //import scanner for input            Scanner input = new Scanner(System.in);               //prompt user input for last name            System.out.print("Enter last name ");            //output for last name            String...
I cant not seem to get this right. I have tried and tried can I please...
I cant not seem to get this right. I have tried and tried can I please get help. Thank you! Writing a Modular Program in Java Summary In this lab, you add the input and output statements to a partially completed Java program. When completed, the user should be able to enter a year, a month, and a day to determine if the date is valid. Valid years are those that are greater than 0, valid months include the values...
I'm trying to make this C++ loan calculator but I can't get the program to output...
I'm trying to make this C++ loan calculator but I can't get the program to output what I need. For instance I know the formula is right and when I enter 100000 1.5 20 as my cin variables I should get 482.55 but I get 1543.31. What am I not seeing as the issue? Also this should cout only 2 decimal places right? I'm not allowed to alter the #include and add any fixed setprecision. This is what I have....
Document the arrays, using a chart with columns titled: outer loop, inner loop, i, j, and...
Document the arrays, using a chart with columns titled: outer loop, inner loop, i, j, and x. Finally, draw a picture of each array (after the program portion has executed). (5 pts) int[][] arr1 = new int[5][5]; int[][] arr2 = new int[5][5]; x = 1; for(int i = 0; I < 5; i++) { for(int j = 1; j < 6; j++) { arr1[i][j-1] = x; x++; if(x == 6) x += 2; } } for(int i = 4; i...
Javascript array of objects: I'm trying to get the input into an array of objects, and...
Javascript array of objects: I'm trying to get the input into an array of objects, and then display the information in a table using a for loop, but I don't think my path is right <!DOCTYPE html> <head> <title>Form</title> <meta charset="utf-8" /> <style media="screen"> h1 { text-align: center; } div { background-color: #pink; border: 2px solid green; padding: 15px; margin: 65px; } </style> <script> var list = []; total = 0; text = ""; function Product(item, quantity, costs){ this.item =...
I need to find the kth smallest element in the union of 2 sorted arrays in...
I need to find the kth smallest element in the union of 2 sorted arrays in O(log |A| + log |B|) time. I understand this is similar to binary search, but I don't understand which parts of the arrays I can throw out at each level of recursion, and why. In the pseudocode below, what should go into $1 through $16 and why? // A and B are each sorted into ascending order, and 0 <= k < |A|+|B| //...
Hello, I Have create this code and Tried to add do while loop but it gives...
Hello, I Have create this code and Tried to add do while loop but it gives me the error in string answar; and the areas where I blod So cloud you please help me to do ( do while ) in this code. // Program objective: requires user to input the data, program runs through the data,calcualtes the quantity, chacks prices for each iteam intered,calautes the prices seperatly for each item, and calculates the amount due without tax, and then...
I have tried this multiple times and I can't get the right answer. The 2014 balance...
I have tried this multiple times and I can't get the right answer. The 2014 balance sheet of Jordan’s Golf Shop, Inc., showed long-term debt of $5.2 million, and the 2015 balance sheet showed long-term debt of $5.45 million. The 2015 income statement showed an interest expense of $170,000. The 2014 balance sheet showed $520,000 in the common stock account and $5.5 million in the additional paid-in surplus account. The 2015 balance sheet showed $560,000 and $5.7 million in the...
Hi: I'm trying to do a lab called " Making solutions with Alkali Halides (And Breaking...
Hi: I'm trying to do a lab called " Making solutions with Alkali Halides (And Breaking Them). The Lab is by John B. Brady. The lab is about X-ray diffraction and I am suppose to answer a few questions and plot the molar composition vs d-values for KCL and NaCl mixture, as well as the d111 for each sample. I have the data but I honestly am comfused about how to stay this lab. Any ideas would be appreciated. Thank...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT