Javascript:矩阵,如何获得不为0的数字的总和 [英] Javascript: matrix, how to get sum of that numbers which are not 0

查看:90
本文介绍了Javascript:矩阵,如何获得不为0的数字的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个F(x)函数,它得到矩阵`

F([

[0,1,5,2],

[1,0,2,0],

[0,0,3,4]

]);

我需要将0以上的数字设为0也是0.因此我必须得到这个'

[

[0,1,5,2],

[0,0,2,0],

[0,0,3,0]

];

然后我需要计算那些不是0的数字的总和。因此我必须得到这个`

13(1 + 5 + 2 + 2 + 3 = 13)。



我尝试了什么:



我试过这样但是它返回11.



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]]));

推荐答案

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



j的值应该从0开始到3(4列),但你的代码从i(可能是0,1或2)到2.所以你将忽略矩阵中的一些列。


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.


那里这里几乎没有问题。一个是j的起始索引。它应该是0.其次,循环中的代码本身。对于每个项目,您应该检查其上方的项目,而不是下面的项目。一旦i =长度, i + 1 将导致错误。此外,第二个for循环的限制值可以与第一个相同或不同。你基本上有一个数组数组。更一般的解决方案可能是这样的:



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:

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.


这篇关于Javascript:矩阵,如何获得不为0的数字的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆