Search code examples
javascriptarraysmatrixsum

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


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