2
votes

I want to give each cell a random double-digit number between 50-500 i'm trying to use math.floor(math.random() as function but no success so far

also how I can target only one cell, for example i have 5x5 slots 5 rows 5 col, and I want to target the top left cell in the corner alone, and instead of random generated numbers like the rest cells, i want to give it a symbol where i can control it, so if the symbol is in top left corner, i click on middle for example and it moves there, replacing the generated number which was in the middle and keeping the top left right corner empty

sorry for the trouble, any help really appreciated

<html>
<head>
<style>
td{
border:2px solid black;
width:10px;
height:10px;
}
td:hover{background-color:lightgreen;}
.grn{
background-color:green;
color:white;
}
</style>

<body>
<div id='ff'></div>

<script>
var isCol=0;
var board=[];
for(r=0;r<7;r++){
    var line=[];
    for(c=0;c<7;c++){
        line.push(r);
    }
    board.push(line);
}


function prs(c,r){
    showTable(c,r);
    isCol=(isCol+1)%2;
}

function toColor(col,row,chosen_col,chosen_row){
var ret=false;
switch(isCol){
    case 0:
        if(row==chosen_row){
            ret=true;
        }
        break;
    case 1:
        if(col==chosen_col){
            ret=true;
        }
        break;
}

return ret;
}

function showTable(chosen_col,chosen_row){
var str="";
str+="<table border=1>";
for(row=0;row<7;row++){
    str+="<tr>";
    for(col=0;col<7;col++){ 
        str+="<td onclick='prs("+col+","+row+")'";
        if(toColor(col,row,chosen_col,chosen_row)){
            str+=" class='grn' ";
        }
        str+=">";
str+=board[row][col];
        str+="</td>";
    }
    str+="</tr>";
}
str+="</table>";

 document.getElementById("ff").innerHTML=str;
}


showTable(-1);
</script>
</body>
</html>


4
let's count the slots together. 7x7. Now, why each row shows the row index number instead of a random 50-500 one? - Roko C. Buljan
Just out of curiosity, what are you building? What's the thing in having random (and possibly repeated) numbers in cells? - Roko C. Buljan

4 Answers

1
votes

You can try with this.

function randRange(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

const rows = 7;
const cols = 7;

const slots = Array.from(new Array(rows), () =>
  new Array(cols).fill(0).map(() => randRange(50, 500))
);

console.log(slots);
0
votes

I noticed you're using isCol as a toggle every time you click a cell. Instead of adding and then doing modulus; use a boolean.

isCol=false;

function prs(...) {
    showTable(...);
    isCol=!isCol;
}

this way you can make your toColor statement simpler.

if(isCol) {
    return row === chosen_row;
}
else {
    return col === chosen_col;
}
0
votes

Besides Stack Overflow - how to generate a random number in range...
I think you're overcomplicating the code. Here's a suggestion:

const size = 5;
const rand = (min, max) => ~~(Math.random() * (max - min) + min);
let tdEmpty = null;            // A place to store the currently empty cell 

const moveValue = evt => {
  const text = evt.target.textContent; // Get cell text
  if (!text) return;           // Clicked empty one, stop function.
  tdEmpty.textContent = text;  // Move text to the currently empty
  evt.target.textContent = ''; // Clear text from the clicked one
  tdEmpty = evt.target;        // Store the new empty TD cell.
};

const newTD = TR => {
  const td = TR.insertCell();
  const text = tdEmpty ? rand(50, 501) : ""; // Create "num" or "" 
  td.appendChild(document.createTextNode(text));
  td.addEventListener('click', moveValue); // Assign a click callback
  if (!tdEmpty) tdEmpty = td;              // Store the first empty cell
};

const newTR = TABLE => {
  const tr = TABLE.insertRow();
  for (let i=0; i<size; i++) newTD(tr);
};

const table = document.createElement('table');
for (let i=0; i<size; i++) newTR(table);

document.querySelector('#ff').appendChild(table);
td { border: 2px solid black; }
td:hover { background-color: lightgreen; }
<div id='ff'></div>

Useful links:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertRow
https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertCell
https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode
Generating random whole numbers in JavaScript in a specific range?

0
votes

I hope I understand you correctly.

Pay attention to Math.floor(Math.random() * (MAX - MIN + 1)) + MIN, don't forget about "+ 1". Without this you will never get 500 (499 is maximum, I try to prove it in comments).

Also you don't have to create single callback to each cell. Better to create one callback to event "click" on table. And than check in what element this event appear. I recommend you to read something about Event Bubbling and Propagation in JavaScript. It's exectly about your task.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Table</title>
    <style>
        td{
            border:2px solid black;
            width:10px;
            height:10px;
        }

        td:hover{
            background-color:lightgreen;
        }

        .grn {
            background-color:green;
            color:white;
        }
    </style>
</head>
<body>
    <div id="ff"></div>
    <script>
        'use strict';

        const SIZE = 10;        // Size of the table (SIZE x SIZE)
        const MIN = 50;         // Minimal number in cell
        const MAX = 500;        // Maximum number in cell
        const CHOSEN_COL = 0;   // Column where chosen cell is
        const CHOSEN_ROW = 0;   // Row where chosen cell is
        const SYMBOL = 'S';     // Yours 'symbol'

        function showTable() {
            let table = document.createElement('table');
            let chosenTd;   // <td> element of chosen cell

            for (let i = 0; i < SIZE; i++) {
                let tr = document.createElement('tr');
                for (let j = 0; j < SIZE; j++) {
                    let td = document.createElement('td');

                    // 1) Math.random() returns values from 0 (inclusive) to 1 (exclusive)
                    // 2) Math.random() * (MAX - MIN) returns values from 0 (inclusive)
                    // to (MAX - MIN) (exclusive)
                    // 3) Math.random() * (MAX - MIN + 1) returns values from 0 (inclusive)
                    // to (MAX - MIN + 1) (exclusive)
                    // 4) Math.floor(Math.random() * (MAX - MIN + 1)) returns values from 0 (inclusive)
                    // to (MAX - MIN) (inclusive!!!)
                    // 5) Math.floor(Math.random() * (MAX - MIN + 1)) + MIN returns values from
                    // MIN (inclusive) to MAX (inclusive) - exectly what we need
                    //
                    // Pay attention to 'inclusive' and 'exclusive'
                    td.textContent = Math.floor(Math.random() * (MAX - MIN + 1)) + MIN;

                    // Obvious (I hope)
                    if (i == CHOSEN_ROW && j == CHOSEN_COL) {
                        chosenTd = td;
                        chosenTd.className = 'grn';
                        chosenTd.textContent = SYMBOL;
                    }

                    tr.append(td);
                }
                table.append(tr);
            }

            table.onclick = function(e) {
                // If we click not at chosen cell (you call it 'symbol')
                if (e.target != chosenTd) {
                    // Now just free cell where 'symbol' is
                    // And 'move' the 'symbol'

                    e.target.textContent = chosenTd.textContent;

                    chosenTd.className = '';
                    chosenTd.textContent = '';

                    chosenTd = e.target;
                    chosenTd.className = 'grn';
                }
            }

            document.querySelector('#ff').append(table);
        }
    </script>
</body>
</html>

Of course, you also have to check that e.target is a cell, not row or full table, for example. But I'm sure, you can do it by yourself.