two dimensional array horizontal average output

后端 未结 7 485
故里飘歌
故里飘歌 2021-01-24 05:20

I am stuck with a problem and i don\'t know how to put this in a for loop. I need the hotizontal average of the next matrix:

1 2 3 4 5

5 4 3 2 1

3 2 1 4 5


        
相关标签:
7条回答
  • 2021-01-24 05:50

    Do this in the language you want. Either Java, or Javascript. Pick one.

    for (int i = 0; i < rows; ++i)
    {
       double sum = 0;
       for (int j = 0; j < columns; ++j)
       {
          sum = sum + matrix[i][j];
       }
       double avg = sum / columns;
       print(avg);
    }
    

    Basically, this is: for each row in the matrix, create a sum of all elements, and then divide the sum by the number of columns to find the average of the row.

    0 讨论(0)
  • 2021-01-24 05:53

    You can do like follows in javascript :

    Have a div like

    <div id="matrix_output"> </div>
    

    and add the javascript code :

    var dArray = [[1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [3, 2, 1, 4, 5]];
     var texts='';
        for (i=0; i<dArray.length; i++)
        {
            sum=0;        
            for(j=0;j<dArray[i].length;j++){
              sum=sum+dArray[i][j];  
              texts=texts + dArray[i][j] + " \t";  
            }
            avg=sum/dArray[i].length;
            texts= texts + avg + " <br/>" ;
           dArray[i][dArray[i].length]=avg;
    
        }
     document.getElementById("matrix_output").innerHTML=texts;
    

    Check the below link for reference :

    http://jsfiddle.net/xGZPL/

    0 讨论(0)
  • 2021-01-24 05:53

    Use map and reduce.

    var matrix = [[1, 2, 3, 4, 5],[5, 4, 3, 2, 1],[3, 2, 1, 4, 5]]
    var result = matrix.map(row=>row.reduce((a,b) => a+b)/row.length);
    console.log(result.join(', '));

    0 讨论(0)
  • 2021-01-24 05:58

    This piece of code alerts the data structured in a table-like string.

    var dArray = [[1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [3, 2, 1, 4, 5]];
    
    var str = '';
    dArray.forEach(function(arr, index){ 
      var average = arr.reduce(function(sum, item){ return sum + item; })/arr.length;
      str += '\n Array ' + index + ':  ' + arr.join(' ') + '   average: ' + average;
    });
    alert(str);
    
    0 讨论(0)
  • 2021-01-24 06:07

    This will compute and place ur values in a new matrix with the average in the last column.

    double[][] Table = new double[dArray.length][dArray[0].length+1];
    double sum, avg;
    for(int i = 0; i<dArray.length; i++)
    {
        sum = 0;
        for(int j = 0; j<dArray[0].length; j++)
        {
            Table[i][j]=dArray[i][j];
            sum += dArray[i][j];
        }
        avg = sum/dArray[0].length;
        Table[i][dArray[0].length] = avg;
    }
    
    0 讨论(0)
  • 2021-01-24 06:08
    var res = [];
    for(i = 0;i<dArray.length;i++){
    
    var tot=0;
    for(j=0;i<dArray[i].length;j++){
    
    tot +=dArray[i][j];
    
    }
    res.push(tot/dArray[i].length);
    }
    return res;
    
    0 讨论(0)
提交回复
热议问题