Click here to Skip to main content
15,881,709 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a F(x) function which gets matrix`
F([
[0,1,5,2],
[1,0,2,0],
[0,0,3,4]
]);
I need make 0 that numbers which above number also 0. As a result i must get this`
[
[0,1,5,2],
[0,0,2,0],
[0,0,3,0]
];
Then i need count sum of that numbers which are not 0. As a result i must get this`
13(1+5+2+2+3=13).

What I have tried:

I have tried like this but it returns 11.

function F(x){
	var sum = 0;
	for(var i = 0; i < x.length; i++){
		for(var j = i; j < x.length; j++){
			if(x[i][j] == 0){
				x[i+1][j] = 0;
			}
			if(x[i][j] != 0){
				sum += x[i][j];
			}
		}
	}
	return sum;
}
console.log(F([[0,1,5,2],[1,0,2,0],[0,0,3,4]]));
Posted
Updated 26-Jul-18 23:26pm

JavaScript
for(var j = i; j < x.length; j++){

The value for j should be going from 0 to 3 (4 columns) but your code has it going from i (which may be 0, 1 or 2) to 2. So you will be ignoring some columns in the matrix.
 
Share this answer
 
Comments
Suren97 27-Jul-18 4:38am    
this way it gives error` Cannot set property '0' of undefined
Richard MacCutchan 27-Jul-18 4:46am    
What way?
Suren97 27-Jul-18 4:49am    
for(var j = 0; j < 4; j++)
Richard MacCutchan 27-Jul-18 5:19am    
If i has the value 2, it is on the last row, so i+1 is an undefined reference.
Suren97 27-Jul-18 5:21am    
so what should i write bro?
There are few problems here. One is the starting index for j. It should be 0. Second, the code in the loop itself. For every item, you should be checking item above it and not the one below. Once i = length, i + 1 will result in error. Also, the limit value in second for loop may or may not be same as first one. You basically have an array of arrays. A bit more general solutions could be something like this:

JavaScript
function F(x){
	var sum = 0;
	for(var i = 0; i < x.length; i++){
		for(var j = 0; j < x[i].length; j++){
			// Check for previous element
                        if(i>0){
                            if(x[i-1][j] > 0){
                            sum += x[i][j];
                            }
                        }
            else{
            sum += x[i][j];
            }
		}
	}
	
    return sum;
   
}


This still assumes that all sub-arrays have same number of elements. If there are differences in them too, you will need to check for length of previous array.
 
Share this answer
 
v2
Comments
Suren97 27-Jul-18 5:31am    
Bro this is wrong too, it returns 7 instead of 13
dan!sh 27-Jul-18 5:40am    
I am not your bro. Or dear. Or sir. Or anything. Updated the response with missing else block.
Suren97 27-Jul-18 5:49am    
Thank you very much :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900