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

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 =...
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...
Trying to make sure I'm answering these questions correctly. I'm confused on question d. I can...
Trying to make sure I'm answering these questions correctly. I'm confused on question d. I can explain why in terms of concentration gradient and the fact it's in a hypotonice solution which would cause water to go into the blood vessel, but don't know how to answer it in terms of hydrostatic pressure. 6. Imagine blood in a vessel that has an osmolarity of 300 mEq (a measure of the concentration of particles). Now, imagine that the IF around 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...
The source code I have is what i'm trying to fix for the assignment at the...
The source code I have is what i'm trying to fix for the assignment at the bottom. Source Code: #include <iostream> #include <cstdlib> #include <ctime> #include <iomanip> using namespace std; const int NUM_ROWS = 10; const int NUM_COLS = 10; // Setting values in a 10 by 10 array of random integers (1 - 100) // Pre: twoDArray has been declared with row and column size of NUM_COLS // Must have constant integer NUM_COLS declared // rowSize must be less...
I'm getting this error: Exception in thread "main" java.lang.NoSuchMethodError: main I tried using public static void...
I'm getting this error: Exception in thread "main" java.lang.NoSuchMethodError: main I tried using public static void main(String[] args){ but that negates all of the methods that I try to write. I'm just trying to make it so that I can enter values. Thanks. Code below: import java.util.Scanner; public class DataSet2 { private double value; private double sum; private int count; public void add(double value){    System.out.println("Enter values, enter -1 to finish");    Scanner scan = new Scanner(System.in);    value =...
I'm trying to decide if I want to invest in a refinery to upgrade my bitumen...
I'm trying to decide if I want to invest in a refinery to upgrade my bitumen to oil. Currently it costs me $40, to get my bitumen to market, where I am able to sell it for $50 a barrel. If I decided to upgrade, it will costs me an extra $6 a barrel, these will produce 30 liters of oil, which I can sell for $2 each.   Should I expand my business? Select one: a. Yes - 4 b....
Below is a chart I'm trying to fill out for Invertebrates. I wanted to know if...
Below is a chart I'm trying to fill out for Invertebrates. I wanted to know if my answers are correct, and if you can help me fill in the sections that I didn't understand (the blank parts). Thank you! Characteristic Cnidaria Nematoda Platyhelminthes Arthropoda Annelida Porifera Echinodermata Protostome/mouth Eumatozoa Protostome Protostome Protostome Protostome Parazoa Deuterostome Radial symmetry Radial bilateral bilateral bilateral bilateral No symmetry (only sponges) radially symmetrical Monoecious Budding Dioecious Monoecious Dioecious Both Monoecious and Dioecious Monoecious Dioecious Cuticle/exoskeleton...
So, I'm trying to get an average revolutions/minute from an input vector. Here's a sample vector:...
So, I'm trying to get an average revolutions/minute from an input vector. Here's a sample vector: V=[10200 11000 11800 12300 13100 13900 14400 15020 15850 16250] The units are in ms so 10200 is 10.2 seconds. The revolutions is between every successive value. So 11000 - 10200 is 1 revolutions per 800 ms and et cetera. I need help figuring out a code that will allow me find the average cadence from the whole dataset. Thank you in advance
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT