2

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>


John Montgomery
  • 6,739
  • 9
  • 52
  • 68
mikoto dread
  • 176
  • 9

4 Answers4

1

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);
Siva K V
  • 10,561
  • 2
  • 16
  • 29
  • 1
    Your code does not generate a random number anywhere as far as I can see. Try replacing `str+=board[row][col];` with `str+=randRange(50, 500);` – Đinh Carabus Feb 15 '20 at 16:51
  • @mikotodread, I just updated the answer to have random numbers in 7 x 7 matrix in the range of 50, 500. Hope I understand your requirement correct. If you need unique random number, then you can maintain one object and regenerate if exists. – Siva K V Feb 15 '20 at 16:59
  • 1
    old code and new one you just wrote, both works, the same, appericate the help, i just needed to add str+=randRange(50, 500); – mikoto dread Feb 15 '20 at 17:06
0

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;
}
DjayFresh
  • 39
  • 7
0

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?

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • What's the `~~` in the random function? – jsejcksn Feb 15 '20 at 17:00
  • @jsejcksn a lazy way to do `Math.floor()` – Roko C. Buljan Feb 15 '20 at 17:01
  • yes i saw that thread but couldn't quite understand it, i went over it 10+ times, also the new code you wrote, i dont understand half of it, im sorry, i am relying purely on javascript, i only started one month ago learning, i am aware there is many ways to do one thing, and some codes can be give better performance, but i am aiming rather for easy, simple, and understandable for beginner – mikoto dread Feb 15 '20 at 17:02
  • @mikotodread Well, happy JS learning. If you have questions - ask. – Roko C. Buljan Feb 15 '20 at 17:04
0

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.

  • @mikotodread It's a link to HTML element . We need this to check did click be to this element (so we don't have to do anything), or to another element (in this case we 'move' this element). In fact, we can do it without `chosenTd`, it just more comfortable for me. Also, I'm not sure, that undersand correctly what you need. – Sergei Martianov Feb 15 '20 at 17:42
  • 1
    @mikotodread `CHOSEN_COL` and `CHOSEN_ROW` is coordinates of you 'symbol' (I call is 'chosen cell'). `CHOSEN_COL` is number of this cell in column, and `CHOSEN_ROW` in row. We use `i` and `j` to generate the table. And we can say that `i` and `j` coordinates of each cell in table. So `if (i == CHOSEN_ROW && j == CHOSEN_COL)` means, than now we generate chosen cell, and we attach to it special class and put to it special value. I don't now how to say it in more simple way. – Sergei Martianov Feb 15 '20 at 17:53
  • yeah i'm aware of this fact , i understand this part, in red things i dont understand, rest i understand [link](https://prnt.sc/r2srz9) check screen shot – mikoto dread Feb 15 '20 at 17:57
  • 1
    @mikotodread OK, I see your point. Variable `td` is an object of `` HTML element. We append each of these element to `tr`, and every `tr` to `table`. Hope, it's clear. `chosenTd` is just another reference to the one of the `` elements (which is symbol). We have to save it, because we use it in `table.onclick`. – Sergei Martianov Feb 15 '20 at 18:04
  • Ohh, now i understand, so the chosen td, we had to create it so we can give it classes and variables , such as grn and symbol and use it in other places, i understand its purpose now and why it was created which led me to other problem, here [link](https://prnt.sc/r2syhc) – mikoto dread Feb 15 '20 at 18:15
  • Read about **Event Bubbling and Propagation in JavaScript**. Briefly, on click to table we check exectly in what element was this click (`e.target`). If it is not our 'symbol' we put in this element 'symbol', add class, and next it will be `choseTd`. And of course we free old `chosenTd` (put there empty value). – Sergei Martianov Feb 15 '20 at 18:26