I need to get the upper triangle of a matrix by setting everything under the diagonal to 0.
Here is the code I wrote:
#include <iostream>
#include <vector>
using namespace std;
vector<vector <int>> upper_triangle(vector<vector <int>> n) {
int rij = n.size();
int kolom = n.size();
vector<vector<int>> result = n;
for (int i = 0; i < rij; i ) {
for (int j = 0; j < kolom; j ) {
if (i > j) {
result[i][j] = 0;
}
}
return result;
}
}
The output that I get is simply the matrix itself which is not what I need.
{{10,11,12},{13,14,15},{16,17,18}}
{{1,2,3},{4,5,6},{7,8,9}}
{{1,2},{3,4}}
The output I need would be:
{{10,11,12},{0,14,15},{0,0,18}}
{{1,2,3},{0,5,6},{0,0,9}}
{{1,2},{0,4}}
CodePudding user response:
You simply have return result;
in the wrong place. Like this
vector<vector <int>> upper_triangle(vector<vector <int>> n) {
int rij = n.size();
int kolom = n.size();
vector<vector<int>> result = n;
for (int i = 0; i < rij; i ) {
...
}
return result;
}
not this
vector<vector <int>> upper_triangle(vector<vector <int>> n) {
int rij = n.size();
int kolom = n.size();
vector<vector<int>> result = n;
for (int i = 0; i < rij; i ) {
...
return result;
}
}
Of course the point of indenting code is to make errors like this easier to spot.