comparison of two arrays and removing duplicates - c++

Hi Here are my Two Arrays.
A[]={1,2,3,4,5}
B[]={3,4,5}
Expected Output:
C[]={1,2}
Can someone try to explain the solution in c++
Please find the code that i tried.We had some problem uploading the code.Please find the algorithm we tried
1) Taken Two Arrays A and B
2) Array A containing m elements and B contains n elements.m>n
3) Took the inputs for Array A and Array B from Standard Input
4) Comparing the elements in both the Arrays element wise using two for loop
where each element of array A compared with each element of Array B and if
not equal push the element into new array.
But we faced two problems here once in case the first element of Array A not equal to first element of B it will be taken as not a duplicate.But that element will be equal to the last element of array B in that case my code fails.
Next is that we are able to get the elements which are not duplicate from Array A into C but if want to get the elements which are not duplicated from array B into C.Do we need to implement for loop again.?

If you use std::vector, so can use std::find for find a element of B in A.
for(int i = 0; i<B.size(); i++)
std::find(A.begin() ,A.end(), B[i])

Related

How unique() function for array works

int a[4] = {3,1,2,3};
sort(a,a+n);
int j = unique(a,a+n) - a; // j=3
In this code variable j returns total numbers of unique element in the array a. But I couldn't understand how this code is working.
I know that in lists,
list::unique() is an inbuilt function in C++ STL which removes all duplicate consecutive elements from the list. It works only on sorted lists.
std::unique() is going to move the duplicates in the range [a+0, a+n), and it returns a new iterator in that range that will mark the new "end" of the array, i.e, where the first non-unique item is now moved to in the array.
If you then subtract from that iterator the beginning iterator, which you do with unique(a,a+n) - a;, you get the number of elements that are between the start of the array and the new "end". This is how you are able to get the count of the unique elements.
It should be noted that I use "end" here because arrays have a fixed size. You aren't actually changing the size of the array at all, you are just moving the duplicate elements to the back of the array, and keeping the unique elements at the front.
It should also be noted that after this happens, everything at and after the iterator returned by unique() will have an unspecified value. It is legal to set new values to them, but using an unspecified value leads to undefined behavior.

Getting Confused While Interpreting a Statement Of Multidimensional Vectors in c++

I am kind of new to Working With 2D Vectors With C++ , and Often times I get confused while I am
Working With 2D Vectors in C++ . I was going through someone's code and I am getting confused while interpreting this line of code :
vector<vector<int>> dp(n, vector<int>(m));
Here , m and n are number of rows and columns of a Grid .
Can Somebody please explain to me in detail , what does this statement mean ?
This line:
vector<vector<int>> dp(n, vector<int>(m));
is invoking a constructor of std::vector.
For dp, the first argument is the number of elements, and the second argument is the value to be inserted those many times.
The inner vector is not specifying the argument value, which will insert default values (0 in the case of int).
So in this case, you are creating a vector with n rows, where each row has m elements in it, and each of the elements is 0.
http://www.cplusplus.com/reference/vector/vector/vector/
One of the constructors of Vector takes param 1 as the number of elements and 2 as the value of those elements. In this case, you are creating a vector named dp... it will have n elements... and each of those elements will be initialized as a new vector of size m elements.
The n and m values only really pertain to the initial size... Vector will automatically resize itself as new elements are added or as you explicitly tell it to if your expect significant size changes to be coming
You can break it down if it helps
vector<vector<int>> dp(n, vector<int>(m));
is effectively the same as
vector<int> row(m);
vector<vector<int>> dp(n, row);
All the first version does is eliminate the row variable.

Issues inserting an element to an array when the index is at the end and an empty array

First time posting something here. Hope I'm doing it right.
If not let me know.
Here's the issue:
I'm trying to insert an element into a given array.
I added a for loop that checked to see if the numOfElem was equal to zero then a[0] would equal elem, but that didn't help either.
void insertAtIndex(int a[], int numOfElem, int elem, int index)
{
for (int i = numOfElem; i > index; i--)
{
a[i] = a[i-1];
}
a[index] = elem;
numOfElem++;
}
Test Cases:
1:
Initial Array: No elements in the array.
Insert 10 at index 0...
Modified array: No elements in the array.
2:
Initial Array: 1
Insert 20 at index 0...
Modified array: 20
/As you can see here it added the 20 to the correct index, but it deleted the 1 instead of shifting it to the right./
3
Initial Array: 3
Insert 30 at index 1...
Modified array: 3
/It did nothing to this test case. Whenever the element that has to be added is at the end it does not add it, it returns the initial array with no change./
In summary, whenever the index of the element that I​ want to insert would be at the end of the modified array or the array is empty it will not make any changes to the array.
Any tips/advice help. Thank you in advance.
There are several issues with the given example.
You tagged the question with C++, but it is pure C code (see also below)
You are using plain C-Style arrays
You should use C++ STL containers
You need to understand how to pass parameters to a function
You nee to read about the "decay to pointer" topic
You must understand how indices in arrays are counted
The last bullet point is the reeason why your program does not work. Array indices start with 0. So, if you have an array with 3 elements, valid indices are 0,1,2. And NOT and under NO ciumstances 3.
So, if your index is equal to numOfElem you will write to an out of bounds memeory area with a[i] = a[i-1];. This is a major bug and may lead to a catastrophy.
Then, you pass parameter numOfElem by value. Meaning, the compiler makes a copy of this variable and uses the copy in the function. numOfElem++; will work on a local copy and will not increase the variable. A good compiler will warn you. This statement is a "no operation". Please always compile wit ALL warnings enables.
And I hope, but cannot see it, that you do not expect your array to grow dynamically by incrementing a variable.
Many STL containers have insert functions that will do the job.

Merging a 2D array with sorted rows into a big 1D array

Given a 2d array which each row is sorted from left to right, from the smallest to the biggest, I want to sort the entire array into a 1D array from the smallest to the biggest.
the number of rows is N and the number of columns is M.
the complexity I need for it is MNlog(N)
What I had in mind to do, is do some kind of a merge sort on the 2d array and each time send 2 rows for the function and there is the point I got stuck.
the signature I'm given for the function is
void sort_rect(int a[N][M], int b[])
I'm promised the the 1d array of b has enough space for all the element of the 2d array.#C!!!
Using the standard approach (of merging the sorted arrays and then sorting) will give you O(NMLog(NM)).If you want an efficient approach then you should use min Heap data structure.You might want to read about heap data structure.
Create an output array of size N*M.This will hold the output sorted array.
Create a min heap of size N.Insert first element of every sorted array.
Remove the top element(minimum) from heap and put it in the output array.Replace this removed element with the next element from the same array of which this removed element was part.Repeat this until all elements are accounted for.
Complexity will be O(NMLog(N)).
Since all the elements in a[M][N] reside in sequential memory, you can treat that memory as flat. So you sort in place like this:
int *c = (int *)a;
and sort c, given that the size of the array is M*N.
Or you can copy it to b, by defining b like this:
int b[sizeof(a) / sizeof(int)];
memcpy(b, a, sizeof(a));
and now sort b.
Think of a merge sort, but applied to N arrays instead of 2. For each row you could keep an index of currently considered element. Now we need something to compare all the N values (instead of just 2). What you could do is use a heap (priority_queue) with an element structure like this:
struct Element {
int Value;
int Row; //tells you which row in the 2d array the value comes from
}
The algorithm would be as follows:
You add all the values from the column 0 to the priority
queue
Declare an array which will keep your currently considered index for each row. Initialize it to zeros.
In a loop (until you run out of elements)
check the element on the top of the queue (element = queue.top())
add element.Value to the 1d array
increment currently considered index for element.Row
remove the element from the top of the priority queue (queue.pop())
The resulting 1d array is sorted and the complexity is O(MNlog(N)). This is because you considered M*N elements and for each element adding/removing it from the priority_queue took log(N) time, because at any given moment the heap keeps no more than N elements.
I think that treating the 2d array as 1d and sorting would result in MNlog(MN) complexity which is a bit worse.

use memcpy and begin() to copy a sub-array of a multidimensional array

I am trying to use memcy to copy an sub-array of an updated array A into an array B. Both A and B array have the same number of dimensions. The data going into array A is in the order of A.get_size(3) (Let's call dimension N here). Each update N will increase by 3(That means 3 set of data is added queueing in terms of dimension N). I need B to obtain the updated data (sub-array)only and the next copy will replace the previous 3. So I guess copy array A starting from (N-2) into B could do the job.
//initializing a new array B to obtain sub-array from A
array B(A.get_size(0), A.get_size(1), A.get_size(2), 3, A.get_size(4));
//Get the forth dimension N
N=A.get_size(3);
//copy the sub-array of A (from N-2 to N) into B(from 1 to 3 in dimension N)
memcpy(B.begin()+A.get_size(0)*A.get_size(1)*A.get_size(2)*(1)*A.get_size(4), A.begin()+A.get_size(0)*A.get_size(1)*A.get_size(2)*(N-2)*A.get_size(4), sizeof(T)*(A.get_size(0)*A.get_size(1)*A.get_size(2)*A.get_size(4)));
However, this could copy the number of elements but not the data value inside. Does it mean it gets memory leak? How should I make changes? Thanks!
Edited:
Thanks to the comments, I tried to use std::copy instead of memcpy, but this does not work in this case because the array A contain complex float. It gives this error when compiling,
error: no matching function for call to ‘copy(std::complex<float>*, const std::complex<float>*, long unsigned int)’
Anymore ideas except from using std::copy? Thanks!