So I'm working on a code to find the Union, Intersection and Difference between two arrays. I'm done with the Union and Intersection but i just can't figure out the difference(A - B) ,For example A={1,3,6,9,7,9} , B={2,3,-2,9} i want to get A - B = { 1,6,7,0} .
I don't want to use any other library except iostream.
This is my code so far.
/* Prints union of A[] and B[]
SizeA is the number of elements in A[]
SizeB is the number of elements in B[] */
cout << "\nUnion of A and B = "; //
i = 0; j = 0;
while (i < SizeA && j < SizeB)
{
if (A[i] < B[j])
cout << A[i++] << " ";
else if (B[j] < A[i])
cout << B[j++] << " ";
else
{
cout << B[j++] << " ";
i++;
}
}
/* Print remaining elements of the larger array */
while (i < SizeA)
cout << A[i++] << " ";
while (j < SizeB)
cout << B[j++] << " ";
cout << "\nIntersection of A and B = ";
for (i = 0; i < SizeA; i++) //for loop to calculate the intersection of A and B.
{
for (j = 0; j < SizeB; j++)
{
if (A[i] == B[j])
{
cout << A[i] << " ";
}
}
}
This is very bad practice because it's not general, not using a clean function and using plain old arrays but I assumed that you are beginner and have to do it in this way
#include <iostream>
int main()
{
int A [] ={1,3,6,9,7}, Asz = 5, B [] ={2,3,-2,9}, Bsz = 4;
std::cout << "\nThe difference is {";
for( int i = 0; i < Asz; ++i){
int temp = A[i];
bool notFound = true;
for(int j = 0; j < Bsz; ++j){
if(temp == B[j]) notFound = false;
}
if(notFound)
{
if(i < Asz - 1) std::cout << temp << ", ";
else std::cout << temp ;
}
}
std::cout << "}";
}
The way I prefer
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> A = {1,3,6,9,7, 0} , B={2,3,-2,9}, C;
std::sort(A.begin(), A.end());
std::sort(B.begin(), B.end());
std::set_difference(A.cbegin(), A.cend(), B.cbegin(), B.cend(), std::back_inserter(C), std::less<int>{});
for(auto const & el : C)
std::cout << el << ", ";
}
If you could save the intersection, you could then just check each element of A and B against the elements of the intersection. Otherwise, you need two for-loops:
cout << "\nDifference of A and B = ";
for (i = 0; i < SizeA; i++) //for loop to calculate the intersection of A and B.
{
bool found = false
for (j = 0; j < SizeB; j++)
{
if (A[i] == B[j])
{
found = true;
}
}
if (!found) {
cout<<A[i]<<" ";
}
}
for (i = 0; i < SizeB; i++)
{
bool found = false
for (j = 0; j < SizeA; j++)
{
if (B[i] == A[j])
{
found = true;
}
}
if (!found) {
cout<<B[i]<<" ";
}
}
Edit: Never mind, i got the definition of difference wrong (thought it was (A-B) + (B-A)), so only the first for-loop is needed, and there's no point saving the intersection.
Related
So I have array A and B, two of them contain random numbers and I need to write in the C array initially even numbers of A and B and then odd. I have made this wtih vector but I wonder if there is other way to do it like in Javascript there are methods like .unshift(), .push() etc
#include<iostream>
#include<vector>
using namespace std;
int main() {
const int n = 4;
int A[n];
int B[n];
vector<int>C;
for (int i = 0; i < n; i++)
{
A[i] = rand() % 10;
cout << A[i] << " ";
}
cout << endl;
for (int i = 0; i < n; i++)
{
B[i] = rand() % 30;
cout << B[i] << " ";
}
for (int i = 0; i < n; i += 1)
{
if (A[i] % 2 == 0)
{
C.push_back(A[i]);
}
if (B[i] % 2 == 0)
{
C.push_back(B[i]);
}
}
for (int i = 0; i < n; i++)
{
if (A[i] % 2 != 0)
{
C.push_back(A[i]);
}
if (B[i] % 2 != 0)
{
C.push_back(B[i]);
}
}
cout << endl;
for (int i = 0; i < C.size(); i++)
cout << C[i] << " ";
}
I would suggest interleaving A and B initially:
for (int i = 0; i < n; i += 1)
{
C.push_back(A[i]);
C.push_back(B[i]);
}
And then partitioning C into even and odd elements:
std::stable_partition(C.begin(), C.end(), [](int i) { return i % 2 == 0; });
vector::push_back is the simplest way to have a collection that grows as you add things to the end.
Since you have fixed size for A and B, you could make them primitive arrays instead, which is what you have done. But for C you don't know how long it will be, so a collection that has a changeable size is appropriate.
You can use std::array, if you know the size you need in compile time. You can then add using an iterator.
#include<vector>
using namespace std;
int main() {
const int n = 4;
int A[n];
int B[n];
std::array<int, n+n>C; // <-- here
auto C_it = C.begin(); // <-- here
for (int i = 0; i < n; i++)
{
A[i] = rand() % 10;
cout << A[i] << " ";
}
cout << endl;
for (int i = 0; i < n; i++)
{
B[i] = rand() % 30;
cout << B[i] << " ";
}
for (int i = 0; i < n; i += 1)
{
if (A[i] % 2 == 0)
{
*C_it++ = A[i]; // <-- here
}
if (B[i] % 2 == 0)
{
*C_it++ = B[i];
}
}
for (int i = 0; i < n; i++)
{
if (A[i] % 2 != 0)
{
*C_it++ = A[i];
}
if (B[i] % 2 != 0)
{
*C_it++ = B[i];
}
}
cout << endl;
for (int i = 0; i < C.size(); i++)
cout << C[i] << " ";
}
Alternatively if you want to be more safe you can hold the next unwritten index and access elements with C.at(last++) = A[i], which checks for out-of-bounds and throws an exception instead of UB.
well you don't to change much.
first of declare C array as int C[n+n]; and declare a variable for incrementing through c array as int j=0;
and in if statements of loops do this C[j]=A[i]; j++; for first if and C[j]=B[i]; j++; for the second if statements
int main() {
const int n = 4;
int A[n];
int B[n];
int C[n+n];
int j=0;
for (int i = 0; i < n; i++)
{
A[i] = rand() % 10;
cout << A[i] << " ";
}
cout << endl;
for (int i = 0; i < n; i++)
{
B[i] = rand() % 30;
cout << B[i] << " ";
}
for (int i = 0; i < n; i += 1)
{
if (A[i] % 2 == 0)
{
C[j]=A[i];
j++;
}
if(B[i]%2==0){
C[j]=B[i];
j++;
}
}
for (int i = 0; i < n; i++)
{
if (A[i] % 2 != 0)
{
C[j]=A[i];
j++;
}
if (B[i] % 2 != 0)
{
C[j]=B[i];
j++;
}
}
j=0;
cout << endl;
for (int i = 0; i < C[].lenght(); i++)
cout << C[i] << " ";
}
I am trying to do a bubble sort, but I don't know what's happening in my code. I am a noob so sorry if the code I wrote seems obvious ^.^
main() {
int a[5], i, j, smallest, temp;
cout << "Enter 5 numbers: " << endl;
for ( i = 0; i <= 4; i++ ) {
cin >> a[i];
}
for ( i = 0; i <=4; i++ ) {
smallest = a[i];
for ( j = 1; j <= 4; j++ ) {
if ( smallest > a[j] ) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
cout << endl << endl;
for ( i = 0; i <= 4; i++ ) {
cout << a[i] << endl;
}
system("pause");
}
Any answer will be highly appreciated. Thanks!
Your bubblesort almost appears to be a selection sort. Bubblesort looks at pairs of items and swaps them if necessary. Selection sort looks for the lowest item in the rest of the array, and then swaps.
#include <iostream>
#include <utility>
using std::cin;
using std::cout;
using std::endl;
using std::swap;
void bubblesort(int a[5])
{
bool swapped = true;
while (swapped)
{
swapped = false;
for (int i = 0; i < 4; i++)
{
if (a[i] > a[i + 1])
{
swap(a[i], a[i + 1]);
swapped = true;
}
}
}
}
void selectionSort(int a[5])
{
for (int i = 0; i < 4; i++)
{
int smallest = i;
for (int j = smallest; j < 5; j++)
{
if (a[smallest] > a[j])
{
smallest = j;
}
}
if (smallest != i)
{
swap(a[i], a[smallest]);
}
}
}
int main(int argc, char* argv[])
{
int a[5];
cout << "Enter 5 numbers: " << endl;
for (int i = 0; i < 5; i++ )
{
cin >> a[i];
}
//selectionSort(a);
bubblesort(a);
cout << endl << endl;
for (int i = 0; i <= 4; i++ ) {
cout << a[i] << endl;
}
}
can someone explain when this line of code ends ? :
void constituteSubsequence(int i){
if( Pred[i] + 1) constituteSubsequence(Pred[i]);
cout << a[i] << " ";
}
In this program that calculate the longest increasing subsequence :
#include <iostream>
using namespace std;
int Pred[1000]; //Pred is previous.
int a[1000], v[1000], n, imax;
void read() {
cout << " n = ";
cin >> n;
cout << " Sequence: ";
for (int i = 0; i < n; i++) {
cin >> a[i];
}
}
void constituteSubsequence(int i) {
if (Pred[i] + 1) constituteSubsequence(Pred[i]);
cout << a[i] << " ";
}
void calculate() {
int i, j;
v[0] = 1;
imax = 0;
Pred[0] = -1;
for (int i = 1; i < n; i++) {
v[i] = 1;
Pred[i] = -1;
for (int j = 0; j < i; j++) {
if (a[j] < a[i] && v[j] + 1 > v[i]) {
v[i] = v[j] + 1;
Pred[i] = j;
}
if (v[i] > v[imax]) {
imax = i;
}
}
}
}
void write() {
cout << " Longest Increasing Subsequence : ";
constituteSubsequence(imax);
cout << endl << " Length: " << v[imax];
}
int main() {
read();
calculate();
write();
return 0;
}
If I run this code,it compiles and works as expected,but how does that condition repeat itself after it found a 0 value (false) and it print cout << a[i] ? .And when does it stop ?
In C++ an integer expression can be treated as a Boolean. For example, in the context of if statement Pred[i] + 1 means (Pred[i] + 1) != 0
This provides the answer to your question: the chain of recursive invocations is going to end when Pred[i] is -1. Of course, an easier to read way to express the same condition would be with the != operator:
if( Pred[i] != -1) {
constituteSubsequence(Pred[i]);
}
const int N=10;
int main()
{
int arr[N]={4,4,6,4,6,6,7,9,9,9};
for (int i = 0; i < N; i++)
for (int j=i+1; j<N; j++)
{
if (arr[i]==arr[j])
cout << arr[i];
}
return 0;
}
This gives all the repeated elements (meaning it will give 444,666,999). My problem is that I want the output to be just 4,6,9 and not that 4 was repeated three times. Obviously I gave my global constant a value of 10 but how can i do this for an "n" (unknown) number. Thanks.
At the beginning sort array
sort(arr, arr + n);
Then iterate and find the count of the most repeated element, you can do that like this :
int maxCnt = 0;
int curCnt = 1;
for (int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1]) curCnt++;
else
{
maxCnt = max(maxCnt, curCnt);
curCnt = 1;
}
}
maxCnt = max(maxCnt, curCnt);
then iterate again accumulating curCnt and when curCnt == maxCnt output number
curCnt = 1;
for (int i = 1; i < n; i++) {
if (curCnt == maxCnt) cout << arr[i - 1] << ' ';
if (arr[i] == arr[i - 1]) {
curCnt++;
}
else curCnt = 1;
}
if (curCnt == maxCnt) cout << arr[n - 1] << endl;
This solution will output the most repeated numbers only once.
Use "range based for loop" for unknown array size (N).
Use std::map to calculate the count for each element.
Here is the code:
#include <map>
#include <iostream>
using namespace std;
int main()
{
const int arr[]{ 4,4,6,4,6,6,7,9,9,9 };
// Get count for each element.
map<int, int> elementCount;
for (const auto& e : arr)
{
elementCount[e] += 1;
}
// Get the highest count.
int highestCount = 0;
for (const auto& e : elementCount)
{
cout << e.first << " " << e.second << endl;
if (e.second > highestCount)
{
highestCount = e.second;
}
}
// Get the elements with the hightest count.
cout << endl << "Elements with the hightest count:" << endl;
for (const auto& e : elementCount)
{
if (e.second == highestCount)
{
cout << e.first << " ";
}
}
cout << endl;
return 0;
}
at the moment I have the following code:
for(int i = 0; i < 4; i++){
cout << rowNo[i] << endl;
}
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
cout << rowNo[i] << '.';
cout << rowNo[j] << endl;
}
}
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
for(int k = 0; k < 4; k++){
cout << rowNo[i] << '.';
cout << rowNo[j] << '.';
cout << rowNo[k] << endl;
}
}
}
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
for(int k = 0; k < 4; k++){
for(int l = 0; l < 4; l++){
cout << rowNo[i] << '.';
cout << rowNo[j] << '.';
cout << rowNo[k] << '.';
cout << rowNo[l] << endl;
}
}
}
}
Where rowNo[] is an array {1,2,3,4}
And I was wondering two things:
Can this be simplified, so maybe put into some sort of recursive loop?
Following that, can this then be made for an array of size N?
Your looking for Cartesian_product
With
bool increment(std::vector<std::size_t>& v, std::size_t maxSize)
{
for (auto it = v.rbegin(); it != v.rend(); ++it) {
++*it;
if (*it != maxSize) {
return true;
}
*it = 0;
}
return false;
}
then you can do:
void print_cartesian_product(const std::vector<int>&v, int n)
{
std::vector<std::size_t> indexes(n);
do {
print(v, indexes);
} while (increment(indexes, v.size()));
}
Demo
You are actually trying to print a number encoded in base4 with digit {1, 2, 3, 4}. To achieve it, You only need to define a function to increment by one. I propose a generic solution in the term of amount of number to print and base.
Like others, I use a number to mean "empty digit", and I use zero which is quite convenient.
Complete source code :
#include <iostream>
#include <vector>
bool increment_basep(std::vector<int>& number, int p)
{
int i = 0;
while(i < number.size() && number[i] == p)
{
number[i] = 1;
++i;
}
if(i >= number.size())
return false;
++number[i];
return true;
}
void print_vect(std::vector<int>& number)
{
for(int i = number.size() -1 ; i >= 0; --i)
{
if(number[i] != 0)
std::cout << number[i];
}
std::cout << std::endl;
}
int main() {
int n = 4;
int p = 4;
std::vector<int> num4(n);
std::fill(num4.begin(), num4.end(), 0);
while(increment_basep(num4, p))
{
print_vect(num4);
}
return 0;
}
The increment return whether or not the computation has overflown. When we overflow we know we need to stop.
First solution it comes my mind is that on every loop to put in a buffer and finally to print all the buffers.
I think there are some other ingenious methods
for(int i = 0; i < 4; i++){
put in buffer1 rowNo[i]
for(int j = 0; j < 4; j++){
put in buffer2 rowNo[i],rowNo[j]
for(int k = 0; k < 4; k++){
put in buffer3 rowNo[i],rowNo[j],rowNo[k]
for(int l = 0; l < 4; l++){
put in buffer4 rowNo[i],rowNo[j],rowNo[k],rowNo[l],endl.
}
}
}
}
print(buffer1);
print(buffer2);
print(buffer3);
print(buffer4);
The following is the simplest code I came up with. There has to be a more direct way of doing this though...
It basically introduces a "ghost" index -1, corresponding to an empty place in a number. The ternary operators in the loops conditions are there to avoid duplicates.
int main()
{
int N = 4;
int rowNo[4] = {1, 2, 3, 4};
for (int i = -1; i < N; i++)
for (int j = (i > -1 ? 0 : -1); j < N; j++)
for (int k = (j > -1 ? 0 : -1); k < N; k++)
for (int l = (k > -1 ? 0 : -1); l < N; l++)
{
if (i > -1) std::cout << rowNo[i] << '.';
if (j > -1) std::cout << rowNo[j] << '.';
if (k > -1) std::cout << rowNo[k] << '.';
if (l > -1) std::cout << rowNo[l];
std::cout << std::endl;
}
}
It can of course be generalized to an array of arbitraty size, possibly with some code generation script.