如何从给定表中查找每行和每列的最小值

时间:2017-12-04 11:22:30

标签: javascript

我想找到每一行的最小值也是每列的最小值

  1. 为表生成后生成的每一行和每列添加输入
  2. 想要找到每一行的最小值和每列的最小值
  3. 也是整个表的最小值
  4. 我想在下面给出的小提琴中输入用户值而不是默认值单元格

    [小提琴] [1]

    
    
    (function (window, document, undefined) {
        "use strict";
    
        var wrap = document.getElementById("wrap"),
            setColumn = document.getElementById("column"),
            setRow = document.getElementById("row"),
            btnGen = document.getElementById("btnGen"),
            btnCopy = document.getElementById("btnCopy");
    
        btnGen.addEventListener("click", generateTable);
        btnCopy.addEventListener("click", copyTo);
    
        function generateTable(e) {
            var newTable = document.createElement("table"),
                tBody = newTable.createTBody(),
                nOfColumns = parseInt(setColumn.value, 10),
                nOfRows = parseInt(setRow.value, 10),
                row;
    
            newTable.createCaption().appendChild(document.createTextNode("Generated Table"));
    
            for (var i = 0; i < nOfRows; i++) {
                row = generateRow(nOfColumns);
                tBody.appendChild(row.cloneNode(true));
            }
    
            (wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.children[0]);
        }
    
        function generateRow(n) {
            var row = document.createElement("tr"),
                text;
    
            for (var i = 0; i < n; i++) {
                text = document.createTextNode(Math.trunc(100 * Math.random()));
                row.insertCell().appendChild(text.cloneNode(true));
            }
            
            return row.cloneNode(true);
        }
    
        function copyTo(e) {
            prompt("Copy to clipboard: Ctrl+C, Enter", wrap.innerHTML);
        }
    }(window, window.document));
    &#13;
    ul {
        margin-left: 0;
        padding-left: 0;
        width: 200px;
    }
    ul li {
        list-style: none;
        padding-bottom: 1em;
    }
    input[type=number] {
        width: 70px;
        float: right;
    }
    table, td {
        border: 1px solid #000;
        padding: 5px;
        border-spacing: 0;
        border-collapse: collapse;
        caption-side: bottom;
    }
    &#13;
    <ul>
        <li>
            <label for="column">Add a Column</label>
            <input type="number" id="column" validate />
        </li>
        <li>
            <label for="row">Add a Row</label>
            <input type="number" id="row" />
        </li>
        <li>
            <input type="button" value="Generate" id="btnGen" />
            <input type="button" value="Copy to Clipboard" id="btnCopy" />
        </li>
    </ul>
    <div id="wrap"></div>
    &#13;
    &#13;
    &#13;

    请给我关于它的建议

    我也希望存储每行和每列的最小值。

1 个答案:

答案 0 :(得分:1)

检查

const generate = document.getElementById('generate');
function handleTable(cont) {
  const table = cont.getElementsByTagName('table')[0],
    cells = table.getElementsByClassName('cell'),
    all_cells = table.getElementsByTagName('td'),
    size = cells.length;
  let currentValue, minimum;
  const p = document.createElement('p'),
    text = document.createTextNode('Minimum is: '),
    minValue = document.createElement('span');
  p.appendChild(text);
  p.appendChild(minValue);
  cont.appendChild(p);
const rowsNum = table.getElementsByTagName('tr').length,
  colsNum = table.getElementsByTagName('td').length/(rowsNum);
const addInput = function(e){
  currentValue = e.target.innerHTML;
  e.target.innerHTML = '';
  let myInput = document.createElement('input');
  myInput.classList.add('my_input');
  e.target.appendChild(myInput).focus();
}
const getMinimum = function(){
  let cur_rows = [],
    temp2 = rowsNum-1;
  while(temp2--)
    cur_rows.push([]);
  let cur_cols = [],
    temp1 = colsNum-1;
  while(temp1--)
    cur_cols.push([]);
  let values = [];
  for (let i = 0; i < size; i++){
    let item = cells[i].innerHTML;
    if(item){
      values.push(item);
      let cur_x = i % (colsNum-1),
        cur_y = (i - cur_x) / (colsNum-1);
      cur_cols[cur_x].push(item);
      cur_rows[cur_y].push(item);
    }
  }
  let cur_min = Math.min.apply(null, values);
  minValue.innerHTML = ((cur_min && (cur_min != Infinity)) || (cur_min == 0)) ? cur_min : '';
  let cur_min_rows = [];
  for (let i = 0; i<cur_rows.length; i++)
    cur_min_rows[i] = Math.min.apply(null, cur_rows[i]);
  let cur_min_cols = [];
  for (let i = 0; i < cur_cols.length; i++)
    cur_min_cols[i] = Math.min.apply(null, cur_cols[i]);
  for (let i = 0; i < all_cells.length; i++)
    if (all_cells[i].classList.contains('result')){
      let cur_x = i % colsNum,
        cur_y = (i - cur_x)/(colsNum);
      all_cells[i].innerHTML = '';
      if ((cur_x == colsNum-1) && (cur_min_rows[cur_y] != Infinity))
        all_cells[i].innerHTML = cur_min_rows[cur_y];
      if ((cur_y == rowsNum-1) && (cur_min_cols[cur_x] != Infinity))
        all_cells[i].innerHTML = cur_min_cols[cur_x];
    }
}
const removeInput = function(e){
  let elem = e.target;
  if (!elem.classList.contains('my_input')) {
    for (let i = size; i--;){
      let input = cells[i].getElementsByClassName('my_input')[0];
      if(input) {
        let value = input.value;
        cells[i].removeChild(input);
        if(value){
          value = value.replace(/ /g,'');
          cells[i].innerHTML = value;
          getMinimum();
        }
        else {
          cells[i].innerHTML = currentValue;
          currentValue = '';
        }
      }
    }
  }
}
for (let i = size; i--;)
  cells[i].addEventListener('click', addInput);
document.body.addEventListener('click', removeInput, true);
};
const generateRow = function(cols, isLast){
  let row = document.createElement('tr');
  const className = (isLast) ? 'result' : 'cell';
  for (let i = cols; i--;) {
    let cell = document.createElement('td');
    cell.classList.add(className);
    row.appendChild(cell);
  }
  let cell = document.createElement('td');
  cell.classList.add('result');
  row.appendChild(cell);
  if(isLast)
    cell.classList.remove('result');
  return row;
}
const generateTable = function(e){
  const wrap = document.getElementById('wrap'),
    rows = document.getElementById('rows'),
    columns = document.getElementById('columns'),
    newTable = document.createElement('table');
  let row;
  for (let i = 0; i <= rows.value; i++ ){
    if(i == rows.value)
      row = generateRow(columns.value, true);
    else
      row = generateRow(columns.value, false);
    newTable.appendChild(row);
  }
  if (wrap.hasChildNodes())
    wrap.innerHTML = '';
  wrap.appendChild(newTable);
  handleTable(wrap);
};
generate.addEventListener('click', generateTable);
.result, .cell{
  width:30px;
  height: 30px;
  text-align:center;
}
.cell {
  border:1px solid;
}
table {
  border-collapse: collapse;
}
.my_input {
  width: 25px;
  text-align:center;
  border:none;
  outline:none;
}
ul {
  width: 200px;
}
ul li {
  list-style: none;
  margin-bottom: 12px;
}
input[type=number] {
  width: 70px;
  float: right;
}
<form>
  <ul>
    <li>
      <label>Rows</label>
      <input type="number" id="rows" value="">
    </li>
    <li>
      <label>Columns</label>
      <input type="number" id="columns" value="">
    </li>
    <li>
      <input type="button" value="Generate" id="generate">
    </li>
  </ul>
</form>
<div id="wrap"></div>