Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create an array from sum of positive elements from rows in matrix

I want to make an array out of sum of positive numbers in row, but my code counts negative elements if they’re standing in first column. Can I get some help with this please?

My code:

<!DOCTYPE html>
<html>
<head>
    <title>Document</title>
</head>
<body>
    <div id="result-container"></div>
          <script>
          let myArray = [3]; 
        
              for (let i = 0; i < 3; i++) { 
                myArray[i] = [];  
                for (let j = 0; j < 3; j++) { 
                  myArray[i][j] = Math.floor(Math.random() * 20 - 10) + 1;  
                } 
        } 
          
        let output = myArray;

        
        console.log(myArray);
        let F = [];

              for (let i = 0; i < myArray[0].length; i++) {
                let posSum = myArray[i][0];
                for (let j = 1; j < myArray.length; j++) {
                  if (myArray[i][j] > 0) {
                    posSum += myArray[i][j];
                  }

                }
          F.push(posSum);
        }
        output += `Array F: ${F}`;
        console.log(F);
        document.getElementById('result-container').innerHTML = output;
          </script>
</body>
</html>

Example of problem:
problem

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The culprit is this line of code:

let maxElement = myArray[i][0];

Here you’re intentionally setting your counter to the value of the first element inside the array. So if it’s e.g. -1 you’re starting to count from -1 and not zero.

Also the second for-loop increments from element 1 onwards – it should start at index 0.

let myArray = [3];

for (let i = 0; i < 3; i++) {
  myArray[i] = [];
  for (let j = 0; j < 3; j++) {
    myArray[i][j] = Math.floor(Math.random() * 20 - 10) + 1;
  }
}

let output = myArray;


console.log(myArray);
let F = [];

for (let i = 0; i < myArray[0].length; i++) {
  let maxElement = 0;
  for (let j = 0; j < myArray.length; j++) {
    if (myArray[i][j] > 0) {
      maxElement += myArray[i][j];
    }

  }
  F.push(maxElement);
}
console.log(F);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading