How to remove duplicate elements from a c++ Bidimensional array - c++

When creating and duplicating the matrix, it writes it the way I want, my question is how can I eliminate the duplicate elements of matrix1 because I need it to only show me the values of the matrix without showing the duplicates. It would be more or less as follows.
enter number of rows: 3.
enter number of columns: 4.
Original Array:.
3 7 14 2.
6 2 3 15.
10 8 11 6.
Result Array:
3.
7.
14.
2.
6.
15.
10.
8.
11.
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int f = 0;
int c = 0;
cout<<"Ingresar numero de filas: ";
cin>>f;
cout<<"Ingresar numero de columnas: ";
cin>>c;
int matriz[f][c];
int matriz1[f][c];
srand(time(0));
for (int i = 0 ; i < f; i++ )
for (int j = 0 ; j < c ; j++ )
matriz[i][j] = 1 + rand()% 15;
cout<< "Arreglo Original"<< endl;
for (int i = 0 ; i < f; i++ ){
for (int j = 0 ; j < c ; j++ ){
cout<<matriz[i][j]<<" "; }
cout<< endl;
}
cout<< "Arreglo resultante "<<endl;
for (int i = 0 ; i < f; i++ ){
for (int j = 0 ; j < c ; j++ ){
matriz1[i][j] = matriz[i][j];
cout<< matriz1[i][j]<<endl;}
}
return 0;
}

Here you are:
#include <vector>
#include <memory>
#include <bitset>
#include <algorithm>
#include <iterator>
#include <iostream>
int main() {
std::vector<std::vector<int>> example{
{ 3, 7, 14, 2 },
{ 6, 2, 3, 15 },
{ 10, 8, 11, 6 }
};
int const max = 15; // while reading example find out max
auto is_avail = std::make_unique<std::bitset<max + 1>>();
std::vector<int> ans;
for (auto const& v : example) {
for (auto const e : v) {
if (!is_avail->test(e)) {
ans.emplace_back(e);
is_avail->set(e, true);
}
}
}
std::copy(ans.cbegin(), ans.cend(), std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}
In case you want ans to be 2D too replace the code following the line
auto is_avail = std::make_unique<std::bitset<max + 1>>();
with
std::vector<std::vector<int>> ans{ example };
for (auto& v : ans) {
for (auto& e : v) {
if (!is_avail->test(e)) {
is_avail->set(e, true);
}
else {
e = -1; // error state
}
}
}
for (auto const& v : ans) {
for (auto const e : v) {
if (e != -1) {
std::cout << std::setw(2) << e;
}
else {
std::cout << std::setw(2) << ' ';
}
std::cout << '\t';
}
std::cout << '\n';
}
and don't forget to
#include <iomanip>
for std::setw.

Related

How does this loop work (Check Duplicate in array loop)

Beginner programmer here can someone please explain to me how this loop works.
How can the loop detect the duplicate element in the array?
sorry for the simple question.
#include <iostream>
using namespace std;
int main()
{
int num[5];
int numSize = sizeof(num) / sizeof(num[0]);
for(int i = 0; i < numSize; i++)
{
cout << "Enter number : ";
cin >> num[i];
if(i >= 0)
{
for(int j = 0 ; j < numSize; j++)
{
if(num[i] == num[j] && (i != j))
{
i--;
j++;
}
}
}
}
for(int p = 0; p < numSize; p++)
cout << num[p] << " ";
}
Avoid indexing when it is possible. It is not final solution but it may show you right direction.
#include <iostream>
#include <algorithm>
int main()
{
int num[] = { 0, 5, 6, 8, 0, 2, 5, 8 };
std::sort(std::begin(num), std::end(num));
auto it = std::begin(num);
while(1) {
it = std::adjacent_find(it, std::end(num));
if(it != std::end(num)) {
std::cout << "Double pairs " << *it << " and " << *(it+1) << std::endl;
++it;
}
else {
break;
}
}
return 0;
}
Output:
Double pairs 0 and 0
Double pairs 5 and 5
Double pairs 8 and 8

displaying a vector of deques in columns

I'm trying to display a vector of deques (std::vector<std::deque<int>> v) like this
v.at(0).at(0) v.at(1).at(0) v.at(2).at(0) v.at(3).at(0)
v.at(0).at(1) v.at(1).at(1) v.at(2).at(1) v.at(3).at(1)
v.at(0).at(2) v.at(1).at(2) v.at(2).at(2) v.at(3).at(2)
v.at(1).at(3) v.at(3).at(3)
v.at(3).at(4)
The first part of the vector is fixed at 7, the size of the actual columns are dynamic however depending on what the user chooses to do.
I was attempting something like
int row = 0;
int column;
for (column = 0; column < v.at(row).size(); column++){
cout << "v["<< row <<"]["<< column << "]" << v.at(row).at(column) << "\t";
while (row < v.size()){
cout << endl;
row++;
}
}
I'm getting errors like
libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: vector
make: *** [Pile.h] Abort trap: 6
Having one of those blah brain days. Can someone help me print this out the way I want it?
Here is a demonstrative program that shows one of approaches to the task.
#include <iostream>
#include <iomanip>
#include <vector>
#include <deque>
#include <algorithm>
int main()
{
std::vector<std::deque<int>> v =
{
{ 0, 1, 2 },
{ 0, 1, 2, 3 },
{ 0, 1, 2 },
{ 0, 1, 2, 3, 4 }
};
size_t n = std::max_element( v.begin(), v.end(),
[]( const auto &x, const auto &y )
{
return x.size() < y.size();
} )->size();
for ( size_t i = 0; i < n; i++)
{
for ( size_t j = 0; j < v.size(); j++ )
{
std::cout << std::setw( 4 );
if ( i < v[j].size() )
{
std::cout << v[j][i];
}
else
{
std::cout << "";
}
}
std::cout << std::endl;
}
return 0;
}
Its output is
0 0 0 0
1 1 1 1
2 2 2 2
3 3
4
First of all, I suggest to get the max queue size
std::size_t maxQ { 0U };
for ( auto const & q : v )
maxQ = std::max(maxQ, q.size());
Now you can write a loop over (0U, maxQ( (the loop of lines) writing elements when available and space otherwise.
for ( auto i = 0U ; i < maxQ ; ++i )
{
for ( auto j = 0U ; j < v.size() ; ++j )
if ( i < v[j].size() )
; // print v[j][i]
else
; // print space
std::cout << std::endl; // endl of line
}
I leave to you cells printing details

Printing out sum of each pair of vector elements - C++

I'm trying to printing out sum of each pair of adjacent elements in a vector. But the code shown below is not giving me the correct result. Anyone can help me with this?
int main()
{
vector <int> num(10);
vector <int> res(5);
int get = 0;
int range = 0;
for (int i = 0; i != 10; ++i) {
cin >> get;
num.push_back(get);
}
while (range != num.size()) {
int c = 0;
int c1 = c + 1;
res.push_back(num[c] + num[c1]);
if (c == 0)
c = 1;
c *= 2;
++range;
}
cout << res[7];
for (int u = 0; u != res.size(); ++u) {
cout << res[u] << " ";
}
return 0;
}
Update: -
I've changed this code as you mentioned in the comment section, but when I compile it showing me a debug error.
I able to read 1-10 integers into the 'num' vector. But when I hit enter after read all the integers into the vector, this debug error happens.
int main()
{
vector <int> num;
vector <int> res;
int get = 0;
int range = 0;
int c = 0, c1 = 0;
for (int i = 0; i != 10; ++i) {
cin >> get;
num.push_back(get);
}
while (range != num.size()) {
c1 = c + 1;
res.push_back(num[c] + num[c1]);
if (c == 0)
c = 1;
c *= 2;
++range;
}
for (int u = 0; u != res.size(); ++u) {
cout << res[u] << " ";
}
keep_window_open();
return 0;
}
Why are you doing this:
if (c == 0)
c = 1;
c *= 2;
What it does on first iteration is that c = 1 then it multiplies it by 2, so c=2 for 2nd iteration and c1 becomes 3.
So first your code will do num[0] + num[1] and in next iteration it will do num[2] + num[3] and third will do num[4] + num[5] and fourth will do num[8]+num[9] and so on.
I can see two approaches to this:
1) If you want to do adjacent addition like 0+1, 1+2, 2+3 then simply do c++ instead of those three lines of code.
2) If you want to do adjacent addition like 0+1, 2+3, 4+5 you can simply do c = c1+1 instead of those three lines of code.
I think the issue is in the loop increment.
Try this
while (range < num.size())
{
int c = 0;
int c1 = c + 1;
res.push_back(num[c] + num[c1]);
c += 2;
++range;
}
I had to change your code to make it compile and to make it reproducible (a good MCVE doesn't require user input):
#include <iostream>
#include <vector>
int main()
{
const std::vector<int> num =
{ 0, 0,
5, 10,
-5, 5,
3, -20};
std::vector<int> res;
unsigned int range = 0;
int c = 0, c1 = 0;
while (range != num.size()) {
c1 = c + 1;
res.push_back(num[c] + num[c1]);
if (c == 0)
c = 1;
c *= 2;
++range;
}
for (unsigned int u = 0; u != res.size(); ++u) {
std::cout << res[u] << " ";
}
}
Your problem is that you are multiplying c by two, instead of adding two, each iteration.
Here's a more idiomatic version:
#include <iostream>
#include <vector>
int main()
{
const std::vector<int> num
= { 0, 0,
5, 10,
-5, 5,
3, -20, };
std::vector<int> res;
const auto last = num.end();
for (auto it = num.begin(); it != last; ) {
auto v = *it++;
res.push_back(v + (it == last ? 0 : *it++));
}
for (auto v: res)
std::cout << v << " ";
std::cout << std::endl;
}
If this is homework, I suggest you make sure you understand it fully before you hand it in.
One solution using STL iterators:
#include <iostream>
#include <vector>
#include <numeric>
int main()
{
std::vector<int> v
{ 0, 0,
5, 10,
-5, 5,
3, -20};
for(auto& r : v) std::cout << r << "\t"; std::cout << std::endl; // print
//Calculate now the adjacent sum (sum of consecutive elements)
std::adjacent_difference(v.begin(), v.end(), v.begin(), [](const int x, const int y) { return x+y; });//here, set execution policy to parallel if wanted
v.erase(v.begin()); // pop_front
// print now every second element. Change i+=2 to i++ if you want every consecutive sum
for(size_t i = 0; i<v.size(); i+=2) std::cout << v[i] << "\t"; std::cout << std::endl;
return 0;
}
which results in:
0 0 5 10 -5 5 3 -20
0 15 0 -17
The biggest issue I see here, in addition to what was mentioned in the comments, is that you're only incrementing range by 1 instead of 2. This causes your code to overshoot the end of the vector, which means your sum is being corrupted by garbage data.

Ikbal has two arrays a and b of length N, initially all values equals to zero.

I was trying to solve this problem with the following code. But the answers aren't accurate for all inputs.
Problem Statement
Ikbal has two arrays a and b of length N, initially all values equals to zero. We have Q operation. Let's define three types of operations on this arrays:
1 l r c Increase al,al+1,...,ar by c.
2 l r c Increase bl,bl+1,...,br by c.
3 l r Print (al∗bl)+(al+1∗bl+1)+...+(ar∗br) in modulo 1000000007
Input Format
First line of the input consists of N and Q. Next Q lines contain one of the three types of operations.
Constraints
1≤N≤109
1≤Q≤200000
1≤c≤10000
1≤l≤r≤N
Output Format
Whenever you get a type 3 operation, you should print the answer in a new line.
Sample Input
5 3
1 1 5 5
2 2 4 2
3 3 4
Sample Output
20
Explanation
After first operation arrays look like this:
a=5,5,5,5,5
b=0,0,0,0,0
After second operation arrays look like this:
a=5,5,5,5,5
b=0,2,2,2,0
Answer of the third operation: 5∗2+5∗2=20
**MY code **
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
vector<int> a,b,c;
int n,q,r,p;
cin >> n;
cin >> q;
for(int i=0;i<q;i++) {
cin >> r;
a.push_back(r);
if(r==3) {
p = 3;
} else {
p = 4;
}
for(int j=1;j<p;j++) {
cin >> r;
a.push_back(r);
}
}
vector<int> aa(n,0),bb(n,0);
int g,start,endd,val,anss=0;
for(int i=0;i<a.size();) {
if(a[i]==3) {
start = a[i+1]-1;
endd = a[i+2]-1;
if(start==endd) {
anss = (aa[start]*bb[start])%1000000007;
} else {
anss = (aa[start]*bb[start] + aa[endd]*bb[endd])%1000000007;
}
cout << anss << endl;
i+= 3;
} else {
start = a[i+1] - 1;
endd = a[i+2];
val = a[i+3];
if(a[i]==1) {
for(int j=start;j<endd;j++) {
aa[j] += val;
}
} else {
for(int j=start;j<endd;j++) {
bb[j] += val;
}
}
i+= 4;
}
}
/*
for(int i=0;i<n;i++) {
cout << aa[i] << " " ;
cout << bb[i] << endl;
}
for(int i=0;i<a.size();i++) {
cout << a[i] << endl;
} */
return 0;
}
Expected output for given input :
http://i.stack.imgur.com/4OsSo.jpg
It's not an overflow problem. This:
if(start==endd)
anss = (aa[start]*bb[start])%1000000007;
else
anss = (aa[start]*bb[start] + aa[endd]*bb[endd])%1000000007;
is flat wrong. You misread the instructions.
Be careful not to cause overflow.
You have to calculate (al∗bl)+(al+1∗bl+1)+...+(ar∗br), not (al∗bl)+(ar∗br)
At least, the output for the given input
10 20
1 9 9 6768
2 5 5 2202
3 7 7
2 3 9 1167
2 1 7 8465
3 1 5
2 1 1 1860
3 9 9
2 5 5 2153
1 5 7 749
3 1 1
2 8 10 3129
3 1 1
1 2 10 2712
2 1 8 79
1 1 6 4645
1 7 7 1358
3 2 10
1 9 9 8677
3 8 10
is corrected.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int add(int a, int b) {
int r = a + b;
if (r >= 1000000007) r -= 1000000007;
return r;
}
int mul(int a, int b) {
int r = 0;
while (b > 0) {
if (b % 2 != 0) r = add(r, a);
a = add(a, a);
b /= 2;
}
return r;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
vector<int> a,b,c;
int n,q,r,p;
cin >> n;
cin >> q;
for(int i=0;i<q;i++) {
cin >> r;
a.push_back(r);
if(r==3) {
p = 3;
} else {
p = 4;
}
for(int j=1;j<p;j++) {
cin >> r;
a.push_back(r);
}
}
vector<int> aa(n,0),bb(n,0);
int g,start,endd,val,anss=0;
for(int i=0;i<a.size();) {
if(a[i]==3) {
start = a[i+1]-1;
endd = a[i+2]-1;
#if 0
if(start==endd) {
anss = (aa[start]*bb[start])%1000000007;
} else {
anss = (aa[start]*bb[start] + aa[endd]*bb[endd])%1000000007;
}
#else
anss = 0;
if (start <= endd) {
for(int j=start;j<=endd;j++)anss = add(anss, mul(aa[j], bb[j]));
} else {
for(int j=endd;j<=start;j++)anss = add(anss, mul(aa[j], bb[j]));
}
#endif
cout << anss << endl;
i+= 3;
} else {
start = a[i+1] - 1;
endd = a[i+2];
val = a[i+3];
if(a[i]==1) {
for(int j=start;j<endd;j++) {
#if 0
aa[j] += val;
#else
aa[j] = add(aa[j], val);
#endif
}
} else {
for(int j=start;j<endd;j++) {
#if 0
bb[j] += val;
#else
bb[j] = add(bb[j], val);
#endif
}
}
i+= 4;
}
}
/*
for(int i=0;i<n;i++) {
cout << aa[i] << " " ;
cout << bb[i] << endl;
}
for(int i=0;i<a.size();i++) {
cout << a[i] << endl;
} */
return 0;
}

Solving a simple matrix in row-reduced form in C++

Okay, I am pulling out all my hair on this one, though, as a noob, I am sure there are several problems. I want to take a matrix and, by sing elementary row operations, reduced it to row-reduced echelon form. We assume (1) it is solvable and (2) a unique solution. There is no checking for zeros or anything; it just does row operations. Here is the code:
#include <iostream>
#include <cstdlib>
using namespace std;
void printmatrix(float A[][4]);
void RowReduce (float A[][4]);
int main() {
// answer should be { 2, 4, -3 }
float A[3][4] = {
{ 5, -6, -7, 7 },
{ 3, -2, 5, -17 },
{ 2, 4, -3, 29 }
};
printmatrix(A);
RowReduce(A);
}
// Outputs the matrix
void printmatrix(float A[][4]) {
int p = 3;
int q = 4;
for (int i = 0; i < p; i++) {
for (int j = 0; j < q; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
}
void RowReduce (float A[][4]){
//rows
int p = 3;
//columns
int q = 4;
// the determines the column we are at which holds the diagonal,
// the basis for all elimination above and below
int lead = 0;
cout << endl;
while ( lead < q - 1 ) {
// for each row . . .
for (int i = 0; i < p; i++) {
// ignore the diagonal, and we will not have a tree rref
// as the diagonal will not be divided by itself. I can fix that.
if ( i != lead ) {
cout << A[lead][lead] << " " << A[i][lead];
for (int j = 0; j < q; j++) {
//here is the math . . . . probably where the problem is?
A[i][j] = A[lead][lead] * A[i][j];
A[i][lead] = A[i][lead] * A[lead][j];
A[i][j] = A[i][j] - A[i][lead];
}
cout << endl;
}
}
// now go to the next pivot
lead++;
cout << endl;
}
}
I tried doing it by hand, but what I get is, of course, the right answer, but this gets a diagonal matrix--which is great--but the wrong answer!
The main error in you code is that you are calculating the divisor or multiplier within the for loop. You should calculate them before iterating over the cells.
Hint: debugging is easier if the code is well formated and the variables have meaningful names.
See the implementation of RowReduce():
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
void printmatrix(float A[][4]);
void RowReduce(float A[][4]);
int main()
{
float A[3][4] = {{5, -6, -7, 7},
{3, -2, 5, -17},
{2, 4, -3, 29}}; //answer should be {2, 4, -3}
printmatrix(A);
RowReduce(A);
}
void printmatrix(float A[][4]) // Outputs the matrix
{
int p=3;
int q=4;
for (int i=0; i<p; i++) {
for (int j=0; j<q; j++) {
cout << setw(7) << setprecision(4) << A[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
void RowReduce(float A[][4])
{
const int nrows = 3; // number of rows
const int ncols = 4; // number of columns
int lead = 0;
while (lead < nrows) {
float d, m;
for (int r = 0; r < nrows; r++) { // for each row ...
/* calculate divisor and multiplier */
d = A[lead][lead];
m = A[r][lead] / A[lead][lead];
for (int c = 0; c < ncols; c++) { // for each column ...
if (r == lead)
A[r][c] /= d; // make pivot = 1
else
A[r][c] -= A[lead][c] * m; // make other = 0
}
}
lead++;
printmatrix(A);
}
}
The output:
5 -6 -7 7
3 -2 5 -17
2 4 -3 29
1 -1.2 -1.4 1.4
0 1.6 9.2 -21.2
0 6.4 -0.2 26.2
1 0 5.5 -14.5
0 1 5.75 -13.25
0 0 -37 111
1 0 0 2
0 1 0 4
0 0 1 -3