如何计算网格中随机数的平均值?

时间:2018-09-11 16:44:05

标签: javascript

我有一个随机的网格生成器,询问您想要多大的网格。如果您输入5,则会生成其中带有随机数的5x5网格,或具有随机数等的10x10网格。

现在,一旦生成网格,我就需要获取这些随机数,并显示随机数的平均值。我似乎无法使该部分正常工作,因为每次生成新网格时都有不同的数字。

var button = document.getElementById('gridSize');

button.onclick = function(e) {
  result = document.getElementById('wrapper');
  num = parseInt(document.getElementById('grid').value);
  var str = "<table border='2'>";

  for (row = 0; row < num; row++) {
    str += "<tr>";
    for (col = 0; col < num; col++) {
      var randNumber = Math.floor(Math.random() * 100) + 1;
      if (randNumber % 3 === 0) {
        str += '<td style="background: red;">';
      } 
      else if (randNumber % 2 === 0 && !randNumber % 3 === 0) {
        str += '<td style="background: blue;">';
      } 
      else {
          str += "<td>";
      }

      str += randNumber + "</td>";
    }
    str += "</tr>";
  }
  str = str + "</table>";
  result.innerHTML = str;    
}
<form name="tablegen">
  <input type="text" name="grid" id="grid"/>
  <input name="generate" id="gridSize" type="button" value="Generate Grid!" onclick='createTable();'/>
</form>

<div id="wrapper"></div>

这是我的代码,我似乎无法弄清楚该怎么做。

4 个答案:

答案 0 :(得分:2)

这是一种简单的方法,只需累加您计算出的randNumber,然后除以单元格总数即可。

var button = document.getElementById('gridSize');

button.onclick = function(e) {
  result = document.getElementById('wrapper');
  num = parseInt(document.getElementById('grid').value);
  var avg = 0;
  var str = "<table border='2'>";

  for (row = 0; row < num; row++) {
    str += "<tr>";
    for (col = 0; col < num; col++) {
      var randNumber = Math.floor(Math.random() * 100) + 1;
      avg += randNumber;
      if (randNumber % 3 === 0) {
        str += '<td style="background: red;">';
      } 
      else if (randNumber % 2 === 0 && !randNumber % 3 === 0) {
        str += '<td style="background: blue;">';
      } 
      else {
          str += "<td>";
      }

      str += randNumber + "</td>";
    }
    str += "</tr>";
  }
  avg /= num*num;
  str = str + "</table>" + "<span>Average is " + avg + "</span>";
  result.innerHTML = str;    
}
<form name="tablegen">
  <input type="text" name="grid" id="grid"/>
  <input name="generate" id="gridSize" type="button" value="Generate Grid!" onclick='createTable();'/>
</form>

<div id="wrapper"></div>

答案 1 :(得分:1)

好吧,创建一个变量,在其中您不断求和所有生成的随机数。

最后,获取该数字并除以网格的面积(用户键入的数字*用户键入的num*num的数字)

像下面这样:

var button = document.getElementById('gridSize');

button.onclick = function(e) {
  var total = 0;
  result = document.getElementById('wrapper');
  num = parseInt(document.getElementById('grid').value);
  var str = "<table border='2'>";

  for (row = 0; row < num; row++) {
    str += "<tr>";
    for (col = 0; col < num; col++) {
      var randNumber = Math.floor(Math.random() * 100) + 1;
      if (randNumber % 3 === 0) {
        str += '<td style="background: red;">';
      } 
      else if (randNumber % 2 === 0 && !randNumber % 3 === 0) {
        str += '<td style="background: blue;">';
      } 
      else {
          str += "<td>";
      }
      total += parseInt(randNumber); 
      str += randNumber + "</td>";
    }
    str += "</tr>";
  }
  str = str + "</table>";
  result.innerHTML = str;    
  console.log("Avg.: ", total/(num*num) || 0)
}
<form name="tablegen">
  <input type="text" name="grid" id="grid"/>
  <input name="generate" id="gridSize" type="button" value="Generate Grid!" onclick='createTable();'/>
</form>

<div id="wrapper"></div>

答案 2 :(得分:1)

您在开始时给我们提供了一些补充。

var button = document.getElementById('gridSize');
var total = 0;
var divisor = 0;

button.onclick = function(e) {
  result = document.getElementById('wrapper');
  num = parseInt(document.getElementById('grid').value);
  var str = "<table border='2'>";

  for (row = 0; row < num; row++) {
    str += "<tr>";
    for (col = 0; col < num; col++) {
      var randNumber = Math.floor(Math.random() * 100) + 1;
      total = total+randNumber;
      ++divisor;
      if (randNumber % 3 === 0) {
        str += '<td style="background: red;">';
      } 
      else if (randNumber % 2 === 0 && !randNumber % 3 === 0) {
        str += '<td style="background: blue;">';
      } 
      else {
          str += "<td>";
      }

      str += randNumber + "</td>";
    }
    str += "</tr>";
  }
  str = str + "</table>";
  result.innerHTML = str;
  var average = total / divisor;
  var averageSpan = document.getElementById('average');
  averageSpan.innerText = average;
}
<form name="tablegen">
  <input type="text" name="grid" id="grid"/>
  <input name="generate" id="gridSize" type="button" value="Generate Grid!" onclick='createTable();'/>
</form>


Average: <span id="average"></span>
<div id="wrapper"></div>

还有个小提琴:https://jsfiddle.net/xpvt214o/775850/

答案 3 :(得分:0)

已经有一些好的答案。这是另一种方法。我还“清理”了HTML并编写了一些代码:

let button = document.getElementById("generatorButton");

button.onclick = function(e) {
    document.getElementById("grid").innerHTML = createGrid();
    document.getElementById("full-average").innerText = getGridAverage();
    document.getElementById("mod3-average").innerText = getGridAverage(".mod3");
    document.getElementById("mod2-average").innerText = getGridAverage(".mod2");
}

function createGrid()
{
    gridSize = parseInt(document.getElementById('gridSize').value);
    let str = "<table border='2'>";
    for (let row = 0; row < gridSize; row++) {
        str += "<tr>";
        for (let col = 0; col < gridSize; col++) {
            var randNumber = Math.floor(Math.random() * 100) + 1;
            if (randNumber % 3 === 0) {
                str += '<td class="mod3">';
            } 
            else if (randNumber % 2 === 0) {
                str += '<td class="mod2">';
            } 
            else {
                str += "<td>";
            }

            str += randNumber + "</td>";
        }
        str += "</tr>";
    }
    str = str + "</table>";
    return str;
}

function getGridAverage(cssClass)
{
    if (cssClass == undefined) cssClass = "";

    let cells = document.querySelectorAll("#grid td" + cssClass);
    if (cells.length > 0)
    {
        let sum = 0;
        for (const cell of cells)
        {
           sum += parseInt(cell.innerHTML);
        }
        return sum / cells.length;
    }
    else
        return 0;
}
.mod3 {
  background-color: red;
}

.mod2 {
  background-color: blue;
}
<form name="tablegen">
    <input type="text" id="gridSize" placeholder="Enter grid size (e.g.: 5)" />
    <input type="button" id="generatorButton" value="Generate Grid!" />
</form>

<div id="grid"></div>

<div>Full Average:<span id="full-average">n/a</span></div>

<div>Mod3 (red) Average:<span id="mod3-average">n/a</span></div>

<div>Mod2 (blue) Average:<span id="mod2-average">n/a</span></div>