how to compute value of intersection of two arrays? - c++

I was able to write a function that prints out the intersection of two arrays. However, I am trying to obtain the value of the members of the intersection.
If our final intersection is {6, 12} I should return 2 as the value because I have 2 members. My return value is 1 and I don't know what I am doing wrong.
int main()
{
int data1[] = { 3, 6, 9, 12};
int data2[] = { 2, 4, 6, 8, 10, 12 };
int result[] = {};
size_t length1 = sizeof(data1)/sizeof(int);
size_t length2 = sizeof(data2)/sizeof(int);
size_t resultMax= 0;
int i =0;
int j =0;
while (i < length1 && j < length2)
{
if (data1[i] < data2[j])
{
i++;
}
else if (data2[j] < data1[i])
{
j++;
}
else if (data1[i] == data2[j])
{
result[i] = data1[i];
cout << "valor : " << result[i] << endl; // output is 6 and 12
i++;
j++;
resultMax = sizeof(result[i])/sizeof(int);
}
}
cout << "Final Size: "<< resultMax; //output is 0
return resultMax;
}

Use std::vector instead of array.
# include<iostream>
# include<vector>
using namespace std;
int main()
{
vector<int> data1 = { 3, 6, 9, 12}, data2 = { 2, 4, 6, 8, 10, 12 }, result;
int i = 0, j = 0, length1 = data1.size(), length2 = data2.size();
while (i < length1 && j < length2)
{
if (data1[i] < data2[j])
i++;
else if (data2[j] < data1[i])
j++;
else if (data1[i] == data2[j])
{
result.push_back(data1[i]);
cout << "valor : " << data1[i] << endl;
i++;
j++;
}
}
cout << "Final Size: "<< result.size();
return 0;
}
Live Code

Use the algorithm library, specifically std::set_intersection.
The following is a slightly adapted example from the above linked cppreference page:
int main()
{
std::vector<int> v1{3, 6, 9, 12};
std::vector<int> v2{2, 4, 6, 8, 10, 12 };
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::vector<int> v_intersection;
std::set_intersection(v1.begin(), v1.end(),
v2.begin(), v2.end(),
std::back_inserter(v_intersection));
std::cout << "Final Size: "<< v_intersection.size();
}

Related

How Do I Get a subvector from a vector?

How do i access 1,2,10 from the below vector?
D = [[1, 2, 10], [2, 3, 20], [2, 5, 25]]
int i=B[i][0]-1;
int j <= B[i][1]-1;
Was Solving a Problem, I Had to use them in a for loop to check for the answer. Can Anyone help me out
Are you looking for this?
#include <iostream>
#include <vector>
int main()
{
std::vector<std::vector<int>> d = { {1, 2, 10}, {2, 3, 20}, {2, 5, 25} };
auto subvector = d[0];
for (auto& value : subvector)
{
std::cout << value << ' ';
}
std::cout << "\n";
// or (poor solution)
for (int i = 0; i < 3; i++)
{
std::cout << subvector[i] << ' ';
}
std::cout << "\n";
// or even
for (int i = 0; i < 3; i++)
{
std::cout << d[0][i] << ' ';
}
std::cout << "\n";
}

How to compare an element of array with all the elements of another array

I have 2 arrays : a [ ] = {1,2,3,4,5,6} and b [ ] = {1,2,6}. How can I compare all elements from array a with all from array b. For example, I compare the first element from a with all elements from b, and if they are not equal, it's displayed and continue to check. So after all I need to get c [ ] = {3,4,5}.
Please help me.
for(i=0;i<n;i++)
{
for(j=0;j<k;j++)
{
if(sf[i].r != temp[j].r)
{
cout<<sf[i].r<<" ";
}
}
}
Where sf[ ] .r = {1,2,2,2,3,5,6,6,7,8,8} and temp[ ].r = { 1,3,5,7} . Output must be {2,2,2,6,6,8,8}.
Just use a std::vector<int> to build up your results, something like:
std::vector<int> set_difference;
for (int elem_a : a)
{
if (std::find(std::begin(b), std::end(b), elem_a) == std::end(b))
{
set_difference.push_back(elem_a);
}
}
int a[] = { 1, 2, 3, 4, 5, 6 };
int b[] = { 1, 3, 6, 2, 5, 9 };
std::vector<int> c;
for (int i = 0; i < sizeof(a); i++)
{
for(int j = 0; j < sizeof(b); j++)
{
if (a[i] == b[j])
std::cout << a[i] << " equals " << b[j] << std::endl;
else
{
std::cout << a[i] << "not equals " << b[j] << std::endl;
c.push_back(a[i]);
}
}
}

Find largest Max list in an array

I need to find the first Max list of an array and find it's middle. In other words, having for example this array {2, 8, 8, 8, 8, 8, 6, 3, 8, 8, 8} I need to have as a result the index 3, which is the middle of the first max list. I did try but my C++ code is still missing something. Can you please help.
Thanks
The following code is just a sample what I'm working on is an 90 elements array.
#include <iostream>
using namespace std;
int main()
{
int array[] = {2, 8, 8, 8, 8, 8, 6, 8, 0};
int Max = 0;
int StartMax = 0, EndMax = 0;
for (int m = 0 ; m < 9 ; m++){
if(array[m] > Max){
Max = array[m];
StartMax = m;
EndMax = m;
cout << "array[m] > Max " << Max << endl;
}
else if(array[m] < Max){
cout << "array[m] < Max " << Max << endl;
}
else {
int a = array[m] - array[m-1];
cout << "a = " << a << endl;
if (a == 0){
cout << "a = " << a << endl;
EndMax = m;
}
}
}
cout << "Index of Max : " << ((StartMax+EndMax)/2) << endl;
}
The problem
Your code work for this example but it won't work when you have a second "max list" which has more than 2 elements.
Indeed with array[] = {2, 8, 8, 8, 8, 8, 6, 8, 8}; (notice the last 8)
We get the result : middle=4 instead of middle3 because you enter this branch condition when you encounter 8 again :
else {
int a = array[m] - array[m-1];
And you enter the branch if (a==0) and you set EndMax to the end of the array !
StartMax = 1 and Endmax = 8 thus middle = 4
This is not what you want !
Live Code
Solution
I would suggest to use a boolean tracker to manage that instead :
size_t give_middle_max_list(const std::vector<int>& v) {
size_t idx_start_max = 0;
size_t idx_end_max = 0;
int max_val = v[0];
bool should_continue = false;
for(size_t i = 1; i < v.size(); i ++) {
if(v[i] > max_val) {
max_val = v[i];
idx_start_max = i;
idx_end_max = i;
should_continue = true;
}
else {
if (v[i] == max_val && should_continue == true) {
idx_end_max = i; // I am still in the first max list
}
else {
should_continue = false; // I am not in the first max list anymore !
}
}
}
std::cout << idx_start_max << ";" << idx_end_max << std::endl;
return (idx_end_max + idx_start_max) / 2;
}
Live code

How do I store numbers that matches in an array?

I want to add the index of arrayOfNumbers that matched to numToMatch to an array. Not sure how to go about this. I'm new to C++. Any help would be appreciated ty.
int numToMatch[4] = {1,2,3,4};
int arrayOfNumbers[7] = {0, 1, 2, 3, 4, 5, 6};
int IndexThatMatched[4]; // Want to add to this Array.
int main()
{
for(int i = 0; i < 4; i++)
{
for(int j = 0; j < 7; j++)
{
if(numToMatch[i] == arrayOfNumbers[j])
{
cout << "Num " << numToMatch[i] << " ";
cout << "matches " << arrayOfNumbers[j];
cout << endl;
}
}
}
}
Added only two lines.
int numToMatch[4] = {1,2,3,4};
int arrayOfNumbers[7] = {0, 1, 2, 3, 4, 5, 6};
int IndexThatMatched[4]; // Want to add to this Array.
int main()
{
for(int i = 0; i < 4; i++)
{
IndexThatMatched[i] = -1;
for(int j = 0; j < 7; j++)
{
if(numToMatch[i] == arrayOfNumbers[j])
{
cout << "Num " << numToMatch[i] << " ";
cout << "matches " << arrayOfNumbers[j];
cout << endl;
IndexThatMatched[i] = j;
}
}
}
}
If there was no match for numToMatch[k] then IndexThatMatched[k] will be -1.
In your example IndexThatMatched will be: {1, 2, 3, 4}.
That's because numToMatch's elements are positioned in indices 1-4 of arrayOfNumbers.
Moreover, after that run, for any k in the safe range:
numToMatch[k] == arrayOfNumbers[IndexThatMatched[k]]
If you really want to learn C++ ditch the C-style arrays and start practising with containers. If you combine them with the functions in <algorithm> you can write something like this:
std::vector<int> MatchNums{1,2,3,4};
std::vector<int> NumsToMatch{0, 1, 2, 3, 4, 5, 6};
std::vector<int> MatchedNums;
for ( auto Number:NumsToMatch )
{
auto Match = std::find( MatchNums.begin(), MatchNums.end(), Number );
if ( Match != MatchNums.end() )
{
MatchedNums.push_back( *Match );
}
}
for ( auto i:MatchedNums )
{ //Print out the found numbers:
std::cout << i << std::endl;
}
There's a lot more ways of doing this by combining different algorithms and I encourage you to try and think of as many ways as you can and try them all out.

Randomizing/Modifing Arrays

So I'm trying to randomize an array of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. Then ask for the user to select a position in the array, and modify it. After that, it should display the number the user entered for all of the 10 values. Finally, it will need to get the original array that was randomized and reverse it.
So far, I have this
#include <iostream>
using namespace std;
int array [10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int rarray [10];
int main() {
cout << "Random Array = ";
for (int i = 0; i < 10; i++) {
int index = rand() % 10;
int temp = array[i];
array[i] = array[index];
array[index] = temp;
}
for (int i = 1; i <= 10; i++) {
cout << array[i] << " "; //somehow, this display needs to be entered into another array
}
system("PAUSE");
}
But as stated in the comment, I'm stuck on as how to do this.
You can accomplish this by using std::shuffle, std::copy, and std::reverse from the C++ Standard Library.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int position;
// Get the position to modify and make sure it's within our bounds.
do
{
cout << "Select a position: ";
}
while (!(cin >> position) || position < 0 || position > 9);
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int rarray[10];
// Shuffle the array. We use std::begin and std::end to get the bounds of
// of the array instead of guessing it's size.
std::random_shuffle(std::begin(array), std::end(array));
// Copy it to the new array
std::copy(std::begin(array), std::end(array), rarray);
// Modify the new array and display it. Add your own code here to get the
// value it is modified with.
rarray[position] = 100;
for (auto value : rarray)
cout << value << " ";
cout << endl;
// Reverse the original array and display it
std::reverse(std::begin(array), std::end(array));
for (auto value : array)
cout << value << " ";
cout << endl;
system("PAUSE");
}
or if you are not allowed to use the C++ Standard Library you will need to handle everything manually. This is a tedious task but a great example of why the C++ Standard Library should be leveraged whenever possible. This is also more prone to errors, more difficult to maintain, and ugly to look at.
int main()
{
int position;
do
{
cout << "Select a position: ";
} while (!(cin >> position) || position < 0 || position > 9);
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < 10; i++)
{
int index = rand() % 10;
int temp = array[i];
array[i] = array[index];
array[index] = temp;
}
// Copy the array
int rarray[10];
for (int i = 0; i < 10; i++)
{
rarray[i] = array[i];
}
// Modify the new array and display it
rarray[position] = 100;
for (int i = 0; i < 10; i++)
{
cout << rarray[i] << " ";
}
cout << endl;
// Reverse the old array and display it
for (int i = 0; i < 10 / 2; i++)
{
int tmp = array[i];
array[i] = array[9 - i];
array[9 - i] = tmp;
}
for (int i = 0; i < 10; i++)
{
cout << array[i] << " ";
}
cout << endl;
system("PAUSE");
}
Both implementations are close to your original request but you may need to expand on it a little to match your requirements exactly. They should get you moving along nicely though.