Comparing two arrays and creating third array with common elements - c++

I need to compare two arrays and output another array that shows common elements.
The output I'm expecting with my code is: 0000056789.
Help will be appreciated.
#include <iostream>
using namespace std;
const int CE = 10;
const int TOP = CE-1;
int iArr1[CE]={0,1,2,3,4,5,6,7,8,9};
int iArr2[CE]={5,6,7,8,9,10,11,12,13,14};
int iArr3[CE]={0,0,0,0,0,0,0,0,0,0};
void main()
{
int i;
int j;
int iCarr3 = 0;
for(i=0; i<=TOP; i++)
{
for (j=0; j<=TOP; j++)
{
if (iArr1[i]==iArr2[j])
{
iCarr3++;
iArr3[iCarr3]=iArr2[j];
}
}
}
cout << iCarr3 << endl;
cout << iArr3;
getchar();
}

you are printing the address of your array
to print the elements of an array
for (int i = 0; i < size; i++) // keep track of the size some how
cout<<iArr3[i]<<" ";
P.S: consider sorting the arrays first, and ckecking if iArr1[i] > iArr2[j]that way you won't need to scan all the elements on eavh pass

C++ has a set_intersection algorithm in the Standard Library:
#include <iostream>
#include <algorithm>
int main()
{
const int CE = 10;
int iArr1[CE] = {0,1,2,3,4,5,6,7,8,9};
int iArr2[CE] = {5,6,7,8,9,10,11,12,13,14};
int iArr3[CE] = {0,0,0,0,0,0,0,0,0,0};
std::set_intersection(std::begin(iArr1), std::end(iArr1),
std::begin(iArr2), std::end(iArr2),
std::begin(iArr3));
std::copy(std::begin(iArr3), std::end(iArr3), std::ostream_iterator<int>(std::cout, " "));
}
Output
5 6 7 8 9 0 0 0 0 0
Note
If your arrays aren't already sorted, you could put the data into a std::set first, since std::set_intersection() requires the inputs to be sorted.

Ok I hope this is not homework. The way you have it, the output will be 5678900000. For the output to be as you want change your code to be as such:
for(i=0; i<=TOP; i++)
{
for (j=0; j<=TOP; j++)
{
if (iArr1[i]==iArr2[j])
{
iArr3[iCarr3]=iArr2[j];
}
}
iCarr3++;
}
Then for the output do this:
for(int k = 0; k <= iCarr3; k++)
std::cout << iArr3[iCarr3] << " ";

As your array are sorted, use std::set_intersection. Otherwise you just have to std::sort them before.
But never forget to use the STD library, the code is a lot more compact and readable... And most of the time less buggy and faster that what you'll come with.
http://ideone.com/c3xE3m
#include <algorithm>
#include <iostream>
#include <iterator>
const size_t CE = 10;
int iArr1[CE]={0,1,2,3,4,5,6,7,8,9};
int iArr2[CE]={5,6,7,8,9,10,11,12,13,14};
int iArr3[CE]={0,0,0,0,0,0,0,0,0,0};
int main(int argc, char const *argv[])
{
auto end_elemnt =
std::set_intersection(iArr1, iArr1 + CE,
iArr2, iArr2 + CE,
iArr3);
std::copy(iArr3, end_elemnt, std::ostream_iterator<int>(std::cout, ", "));
return 0;
}
Here is the output:
$ ./a.exe
5, 6, 7, 8, 9,

Related

Problem using iterators with dynamically allocated array

I have a variable k of type int to set the length of a dynamically allocated int array:
int *Numbers = new int[k];
But because of this I cannot iterate over the array, I get an error:
"no matching begin function was found required for this range-based for statement"
I also cannot get the length of the array using size();
Here's the complete code:
#include <iostream>
using namespace std;
int main()
{
int b, k;
cin >> b >> k;
int *Numbers = new int[k];
for (int i : Numbers) {// (There is a error)
}
for (int i = 0; i < size(Numbers); i++) {
}
}
Prefer using a std::vector instead of a std::array. (Like #tadman mentioned.)
Here is your code using std::vector instead:
#include <iostream>
#include <vector>
int main()
{
int b, k;
std::cin >> b >> k;
std::vector<int> Numbers(b,k); // Fills the vector "Numbers" with nth number of elements with each element as a copy of val.
for (int i : Numbers)
std::cout << i << std::endl;
for (int i = 0; i < Numbers.size(); i++)
std::cout << Numbers[i] << std::endl;
return 0;
}
Say I want 10 elements with the number 5.
Output:
10
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
5
Also consider not using namespace std;.
The simple and recommended solution is to use std::vector, however if you really want a dynamically allocated array and to use iterator like features on it, you can use iterator_range from boost library, which allows you to create an iterator range for it thus making it usable in range based for loops and in functions like std::size.
Live demo
#include <iostream>
#include<boost/range.hpp>
int main()
{
int k = 5;
int *Numbers = new int[k]{1,4,5,7,8};
auto arr = boost::make_iterator_range(Numbers, Numbers + k);
for (int i : arr) { //range based loop
std::cout << i << " ";
}
std::cout << std::endl << "Size: " << arr.size(); //print size
//or std::size(arr);
}
Output:
1 4 5 7 8
Size: 5
Range-based for loops work with arrays, but not work with pointers. The Actual issue is that arrays is actually a pointer and not an array.try to use simple array.
Using pointers is problematic for many reasons. The simple solution to your problem is to use a vector
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int b, k;
cin >> b >> k;
vector<int> Numbers(k);
for (int i : Numbers) {
cout << i << endl;
}
for (int i = 0; i < Numbers.size(); i++) {
cout << Numbers[i] << endl;
}
}
C array does not have default iterator and thus there is no begin() and end() functions that are used to iterate over array when you use statment like this:
for (int i : Numbers)
You can check range-for reference:
range_expression - any expression that represents a suitable sequence (either an array or an object for which begin and end member functions or free functions are defined, see below) or a braced-init-list.
Okay, so since the dynamic array does not have a default iterator, do not use the for-each loop, instead consider using the regular for loop.
Also, mind the the size function will not work for an array (or dynamic array) and you need to remember the size, since it's not possible to get the size from the pointer only. Hence, this code would work:
#include <iostream>
using namespace std;
int main()
{
int b, k;
cin >> b >> k;
int *Numbers = new int[k];
const int SIZE = k;
for (int i = 0; i < SIZE; i++) {
cout << i << ' ';
}
}
You need to dereference *Numbers by using the * if you want to iterate over the array because *Numbers is a pointer to an integer which points to the first element of your array.For Example :
#include <iostream>
using namespace std;
int main()
{
int k = 10;
int *numbers = new int[k];
//filling the array
for(int i = 0 ; i < k ; ++i) {
*(numbers + i) = i ;
}
//output array element
for(int i = 0 ; i < k ; ++i) {
cout << numbers + i << " is the address of "<<*(numbers + i) << endl;
}
return 0;
}
The output is :
0x6f1750 is the address of 0
0x6f1754 is the address of 1
0x6f1758 is the address of 2
0x6f175c is the address of 3
0x6f1760 is the address of 4
0x6f1764 is the address of 5
0x6f1768 is the address of 6
0x6f176c is the address of 7
0x6f1770 is the address of 8
0x6f1774 is the address of 9
Unfortunatly, you can't get the size of your array with *Numbers because it's not an array but a pointer.

Is it possible to use std::sort to sort by lexicographic order?

My problem looks like this:
At the beginning u have to insert an amount of numbers.
Next program counts the sum of digits of the number that u inserted in step one.
All scores are inserted in vector called vec
The problem is this: At the end of the program all numbers that You inserted in steps 1, must be sorted depends of theirs sums of digits(Sorting in increasing order).
And ATTENTION please! For example if two of numbers(e.g. 123 and 12300) have the same sum of digits you have to sort them by the lexicographic order.
I don't want to create function build by myself but I would like to use “sort” function from library but I have problem with that..Is it possible to use sort function also to sorting by the lexicographic order? Can someone can help me?
Example input:
6
13
36
27
12
4
123
Expected output:
12
13
4
123
27
36
My code:
#include<iostream>
#include<cmath>
#include<string>
#include<vector>
#include<sstream>
#include<algorithm>
using namespace std;
int main()
{
vector<vector<int> > vec;
int num;
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> num;
vector<int> row;
row.push_back(num);
//conversion int to string:
ostringstream ss;
ss << num;
string str = ss.str();
int sum = 0;
for (int g = 0; g < str.length(); g++){
int pom = str[g] - '0';
sum += pom;
}
row.push_back(sum);
vec.push_back(row);
row.clear();
}
//sort(vec[0][0], vec[vec.size()][0]);
for (int i = 0; i < vec.size(); i++){
for (int j = 0; j < 2; j++){
//cout << vec[i][j] << " ";
}
cout << vec[i][0] << endl;
}
system("pause");
return 0;
}
You could store each number as a string, but also pre-compute its digit-sum and keep both in a pair<int,string>, then put them into a vector<pair<int,string> and sort it. No need for a custom comparator, the one for std::pair does exactly what you want.
// note: std::pair<std::string,int> would not work
typedef std::pair<int,std::string> number;
std::vector<number> numbers;
// fill numbers such that number::first holds the digit sum
// and number::second the number as string.
// this is similar to your code
std::sort(numbers.begin(), numbers.end());
// now numbers are ordered as you want them
Just pass a suitable comparison function (or functor, e.g. a lambda would be natural) to std::sort.
Since you want to compare on sum of digits first and then lexicographically to break ties, it will be convenient to convert your input numbers to strings.
From there you can define a custom comparator to achieve the desired behavior:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int sumDigits(string s)
{
int sum = 0;
for (unsigned int i=0; i<s.length(); ++i)
{
sum += s[i] - '0';
}
return sum;
}
bool digitSumComparator(int i, int j)
{
int iSum = sumDigits(to_string(i));
int jSum = sumDigits(to_string(j));
if (iSum == jSum)
{
return iStr < jStr;
}
else
{
return iSum < jSum;
}
}
int main()
{
vector<int> v {6,13,36,27,12,4,123};
sort(v.begin(), v.end(), digitSumComparator);
for (vector<int>::iterator it=v.begin(); it!=v.end(); ++it)
{
cout << *it << ' ';
}
cout << '\n';
return 0;
}
Output:
$ g++ -std=c++11 digitsumsort.cpp
$ ./a.out
12 13 4 123 6 27 36

Find in array the biggest multiple and write it vica versa

I was given a task:
it is given an array of five numbers
First - Find all numbers that are multiples of four
Second - Find the biggest of them and write it vice versa.
I have written a code.
#include <iostream>
#include <iomanip>
using namespace std;
#define size 12
int main()
{
int new_max=0;
int a1, a2;
int i=0, j=0;
int a, b, c=0;
int u[size]={38,12,36,45,16,46,14,19,54,53,95, 98};
int max=0;
cout<<"Array: \n";
for(i=0; i<size; i++)
cout<<u[i]<<" \n";
for (int i=0; i<size; i++)
{
if (u[i]%4==0)
{
cout<<"array "<<u[i]<<" \n";
for (int j=0; j<size; j++)
{
if(max<u[i])
{
max=u[i];
}}}}
cout<<"max "<<max<<endl;
while(max > 0)
{
new_max = new_max*10 + ( max % 10);
max = max/10;
}
cout << new_max << endl;
return 0;
}
#include <iostream>
#include <algorithm>
#include <string>
#include <array>
int main() {
std::array<int, 5> input = { 36, 12, 38, 45, 16 };
auto validRangeEnd = std::remove_if(std::begin(input),
std::end(input),
[](int i){ return i % 4 != 0; });
// Now std::begin(input) -> validRangeEnd contain the ones divisible by 4
auto max = std::max_element(std::begin(input), validRangeEnd);
// Max contains the max number from the filtered range
auto stringMax = std::to_string(*max);
std::reverse(std::begin(stringMax), std::end(stringMax));
// Reverse reverses the max number
std::cout << stringMax;
}
By no means optimal but I feel it's useful for educational purposes :).
(Both remove_if and max_elements do a pass so I'll re-examine some stuff that I don't need to but this is a good algorithmic representation of the problem anyway. Also, no loops, look! :))

How to implement infinite multidimensional array?

I want to use the code below and I want to use it for "unknown size of input". For example there is an array int cac[1000][1000]. I can use vector<vector<int> > array;, then how can i initialize it with -1 ? Any suggestions?
#include <sstream>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <memory.h>
using namespace std;
int cac[1000][1000];
string res[1000][1000];
vector<string> words;
int M;
int go(int a, int b){
if(cac[a][b]>= 0) return cac[a][b];
if(a == b) return 0;
int csum = -1;
for(int i=a; i<b; ++i){
csum += words[i].size() + 1;
}
if(csum <= M || a == b-1){
string sep = "";
for(int i=a; i<b; ++i){
res[a][b].append(sep);
res[a][b].append(words[i]);
sep = " ";
}
return cac[a][b] = (M-csum)*(M-csum);
}
int ret = 1000000000;
int best_sp = -1;
for(int sp=a+1; sp<b; ++sp){
int cur = go(a, sp) + go(sp,b);
if(cur <= ret){
ret = cur;
best_sp = sp;
}
}
res[a][b] = res[a][best_sp] + "\n" + res[best_sp][b];
return cac[a][b] = ret;
}
int main(int argc, char ** argv){
memset(cac, -1, sizeof(cac));
M = atoi(argv[1]);
string word;
while(cin >> word) words.push_back(word);
go(0, words.size());
cout << res[0][words.size()] << endl;
}
What you can do is to use a associative array, where the key is a pair (rowPosition, ColumnPosition). When you want to set array[i][j] you just add or update the value assoArray[Pair(i,j)]. You can assume that any element which is not in the associative array has the initial value.
In general infinite multidimensional arrays are used for theoretical purpose.I hope i didn't misunderstood the question.
Using std::vector from the STL is much more straightforward than the following solution, which was pointed out in the comments for this post. I find that this site explains that topic effectively: http://www.learncpp.com/cpp-programming/16-2-stl-containers-overview/
An array of infinite size is not actually possible. However, you can achieve basically that effect using dynamic allocation. Here's some sample code:
int counter = 0;
int* myArray = new int[1000];
Fill the array with data, incrementing counter each time you add a value. When counter reaches 1000, do the following:
int* largerArray = new int[2000];
for( int i = 0; i < 1000; i++ )
{
largerArray[i] = myArray[i];
}
delete[] myArray;
myArray = largerArray;
With this method, you create the closest thing possible to an infinitely sized array, and I don't believe performance will be an issue with the copy piece

How to sort C++ array in ASC and DESC mode?

I have this array:
array[0] = 18;
array[1] = -10;
array[2] = 2;
array[3] = 4;
array[4] = 6;
array[5] = -12;
array[6] = -8;
array[7] = -6;
array[8] = 4;
array[9] = 13;
how do I sort the array in asc/desc mode in C++?
To sort an array in ascending, use:
#include <algorithm>
int main()
{
// ...
std::sort(array, array+n); // where n is the number of elements you want to sort
}
To sort it in descending, use
#include <algorithm>
#include <functional>
int main()
{
// ...
std::sort(array, array+n, std::greater<int>());
}
You can pass custom comparison functor to the std::sort function.
Well first I'm hoping your array assignment was just an error when posting but all your numbers are being assigned to the same memory location. There's nothing to sort.
After that, you can use the sort() function. The example linked shows an easy method for using it. Note that there is a third parameter that's not being used that will specify how to compare the elements. By default if you don't specify the parameter it uses 'less-than' so you get an ascending order sort. Change this to specify 'greater-than' comparator to get a descending order sort.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main (int argc, char *argv[])
{
int num[10]={18,-10,2,4,6,-12,-8,-6,13,-1};
int temp;
cout << "Ascending Sort : \n\n";
for(int i=0; i<=10; i++)
{
for(int j=i+1; j<=10; j++)
{
if(num[i]>num[j])
{
temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}
cout << num[i] << "\n";
}
cout << "\nDescending Sort : \n\n";
for(int i=0; i<=10; i++)
{
for(int j=i+1; j<=10; j++)
{
if(num[i]<num[j])
{
temp=num[j];
num[j]=num[i];
num[i]=temp;
}
}
cout << num[i] << "\n";
}
return 0;
}
Generally, you can just swap the two variables in
http://www.cplusplus.com/reference/algorithm/sort/
Change
bool myfunction (int i,int j) { return (i<j); }
to
bool myfunction (int i,int j) { return (j<i); }
you can rename it to something else so that you have two comparison functions to use when the result needs to be ascending or descending.
If the function body has complicated expressions and involves i and j multiple times, then it is easier to swap the i and j in the parameter list instead of every i and j in the body:
bool myfunction (int j,int i) { return (i<j); }
The same goes for
http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/