Reputation: 1345
I won't diguise it: I got an optimization homework for a programming task, and I need a confirmation about that my solution right.
The task is the next: you get a matrix that has random number of rows, and each row has different length. There are sentinels in the matrix we get: there's a -1 value at the end of each row. The last row of the matrix starts with a -1 value. Every other values of the matrix are positive integers and 0.
The task is to find the first row, that has only 0 elements (excluding the sentinel, and write it - also, I have to use only 2 variable, one while
loop, and one condition within it. Writing out may happen with conditions.
Overall, the code must have a general form like this (excluding the definition of the matrix:
//'sor' means row, 'oszlop' means coloumn
int sor, oszlop;
while(){
if(){
}else{
};
}
if (){
cout <<"We couldn't find a row with only 0 elements."<<end;
}else{
cout <<"We could, and this is:"<<end;
}
And this is my code (only the parts inside main()
, and also excludes the definition of the matrix):
int sor=0, oszlop=0;
while (x[sor][oszlop]!=-1){
if (x[sor][oszlop]==0){
++oszlop;
}else{
++sor;
oszlop=0;
}
}
if (oszlop==0){
cout <<"We couldn't find a row with only 0 elements."<<end;
}else{
cout <<"We could, and this is:"<<end;
}
The code skips invalid coloumns, until it reaches the end; or it exits if it can reach the end of any rows - but it can do it only if all of its elements were 0.
It definitely exits in case of finding a -1, but the value of oszlop
decides, whether we found a valid row, or we couldn't, and we exit because of reaching end of the matrix.
I tested it with a random matrix, but I'm still unsure, so I need your confirmation.
Did I do the task well?
Upvotes: 0
Views: 144
Reputation: 218
Did you try testing it on a matrix where the only valid row is the last row? Say for example,
[-1;
-1 0 -1]
Or perhaps
[1 -1;
-1 0 -1]
if every row has to have some element other than -1.
Upvotes: 0