Hi want to create a grid 5 by 5 and fill it randomnly with number using javascript. Can someone help?

Do you have any code to work with as of yet? I am thinking that you can create a grid using a table or div element, assign each cell a unique id from 0-24.

then, in your JavaScript function, reference each element ID within a for loop and then generate …

@techyworld,

Your script is completely wrong. It does NOT create a 2D array but rather create all-undefined-value array size of 10. But then you wrongly assign a value of 1 using an invalid index (not a number). Because JavaScript always trys to fix the user script, it insteads uses your …

## All 7 Replies

Do you have any code to work with as of yet? I am thinking that you can create a grid using a table or div element, assign each cell a unique id from 0-24.

then, in your JavaScript function, reference each element ID within a for loop and then generate the random number using the random() method and assign that value to the innerHTML property of the element.

use this formula to get a random number from 1-10.
`Math.floor((Math.random()*10)+1);`

ok forget the grid. lets generate it as a 2D array. I have done this but its not a 2D array. I want to put it in a 2 Dimensional array. Can i know how to proceed?

``````var string="";
for (var i=0;i<10;++i){
for(var j=0;j<10;++j){
var first =generatecase(0,100000);
if((first %2)==0)
{ string= string+ " "+generate(0,9); }
else{
var second=generate(0,100000);

if((second%2)==0)
{string=string+ " "+ "+";}
else
{string=string+ " "+ "-" ;}

}

}
string=string+"<br>";
}

document.write(string);

function generate(x,y)
{return Math.floor(Math.random() * (x - y + 1)) + y;}
``````

in actionscript I would make it with an array formatted to be understandable eg.

``````var grid = new Array(1,2,3,4,
5,6,7,8,
9,10,11,12,
13,14,15,16,
17,18,19,20,
21,22,23,24);
``````

Once you see that format its much easier to grasp how to make it up, i just done random numbers here since you said afterwards you wanted random not a grid:

``````<html>
<script type='text/javascript'>
function generateRand(){return Math.floor(Math.random()*500);}
var perRow = 4;
var numRows = 6;
var grid = new Array();
grid['x'] = new Array();
grid['y'] = new Array();
for (var i=0; i<numRows; i++){
for (var ii=0; ii<perRow; ii++){
var iii = 0;
if(i == 0){

}else{
iii += (perRow*i);
}
iii += ii;
grid['x'][iii] = generateRand();
grid['y'][iii] = generateRand();
}
}
console.log(grid);
console.log(grid['x']);
console.log(grid['y']);
var obj = new Object();
obj.x = grid['x'][0];
obj.y = grid['y'][0];
console.log(obj);
</script>
<body>
</body>
</html>
``````
``````        var a = new Array(10);
for (i = 0; i < 10; i++) {

for (j = 0; j < 10; j++) {

a[i,j] = 1;
document.write(a[i,j]);
}
}
``````

Ok i manage to write it in 2D array. Now i want to draw a grid of size 10 by 10 and populate it using this 2D array. how can i do this? the code above is for my 2D array. it will display 1 everywhere in the grid. Anyone can tell me how to proceed? i want to do this in javascript.

Ah.. I had just saw this updated thread, but while offline, I had worked on a sample in which a dynamic HTML table is created and then populated by random numbers. In case you still want to see it, take a look at this sample:

How to Create a Dynamic Table with JavaScript

What the demo I worked on does is it creates the table based on the values of two variables in the JavaScript function and populates the cells with random numbers that you also define in two variables.

results displayed in a table...for this example the range is 1-10...

Now i want to draw a grid of size 10 by 10 and populate it using this 2D array. how can i do this? the code above is for my 2D array. it will display 1 everywhere in the grid. Anyone can tell me how to proceed? i want to do this in javascript.

You saw my above post?

@techyworld,

Your script is completely wrong. It does NOT create a 2D array but rather create all-undefined-value array size of 10. But then you wrongly assign a value of 1 using an invalid index (not a number). Because JavaScript always trys to fix the user script, it insteads uses your second argument (j) from [i,j] as index.

``````var a = new Array(3);  // created [undefined, undefined, undefined]
a[2,4] = 1;  // modify it to [undefined, undefined, undefined, undefined, 1]
a[3,1] = 2;  // modify it to [undefined, 2, undefined, undefined, 2]
``````

A proper to create a 2D array is to use iteration.

``````var a = new Array(3);  // created [undefined, undefined, undefined]
for (var i=0; i<a.length; i++) { a[i] = new Array(2); }
/*
now each iteration when i is 0, 1, and 2 will be as follows:
after the i=0, a becomes
[[undefined, undefined], undefined, undefined]
after the i=1, a becomes
[[undefined, undefined], [undefined, undefined], undefined]
after the i=2, a becomes
[[undefined, undefined], [undefined, undefined], [undefined, undefined]]
*/
``````

Below is a quick & dirty implementation of a function that takes 4 variables -- row number, column number, minimum random value, and maximum random value -- instead of fixing most everything as constants, and return a 2D array.

``````<script type="text/javascript">
/*****
* Return a 2D array size of the given number of rows & columns. The values filled
* inside the array are random values between minVal and maxVal -- [minVal, maxVal).
* If minVal is not given, the default value is 0. If the given minVal is greater
* than maxVal, the minimum value used will come from maxVal and the maximum value
* used will come from minVal. Return null if any of the argument is invalid.
*/
function generate2DArrayWithRandomValue(rows, columns, maxVal, minVal) {
if (isNaN(rows) || rows<1 ||        // not valid row value
isNaN(columns) || columns<1 ||  // not valid column value
isNaN(maxVal)) {                // not valid maximum value
return null;
}
minVal = isNaN(minVal) ? 0 : minVal;
var output = new Array(rows);  // create an array with total row number
for (var r=0; r<rows; r++) {
output[r] = new Array(columns);  // create 2nd dimension with total column number
for (var c=0; c<columns; c++) { output[r][c] = getRandomNumber(minVal, maxVal); }
}
return output;  // done
}  // generate2DArrayWithRandomValue

/*****
* Return an integer value between min and max. If min is less than or equal to
* max, return [min, max). If min is equal to max, return the value of min/max.
* If min is greater than max, return [max, min).
* Expecting min & max are numbers.
*/
function getRandomNumber(min, max) {
var diff = max-min;
var range = Math.floor(Math.random()*diff);
return (min+range);
}  // getRandomNumber

/*****
* Display a given array (supposely 2D) using table format inside the given
* div element ID.
* You would need to update this function if you want to change the display
* of the array.
*/
function displayArrayAsTable(outputId, anArray) {
var el = document.getElementById(outputId);
var output = "";
var tdStyle = "border:1px solid black;text-align:center;vertical-align:middle;";
tdStyle += "width:20px;height:20px;";  // add minimum fixed size display
if (el && el.tagName=="DIV") {  // output is OK
output += "<table style=\"border-collapse:collapse\">"
if(anArray instanceof Array) {  // row is OK
for (var r=0; r<anArray.length; r++) {  // go through each row
output += "<tr>"
if (anArray[r] instanceof Array) {
for (var c=0; c<anArray[r].length; c++) {
output += "<td style=\""+tdStyle+"\">"+anArray[r][c]+"</td>"
}
}
else {  // not a 2D array, so it is simply an element
output += "<td style=\""+tdStyle+"\">"+anArray[r]+"</td>"
}
output += "</tr>"
}
}
else { output += "<tr><td>"+anArray+"</td></tr>" }
output += "</table>"
el.innerHTML = output;
}
}  // displayArrayAsTable
</script>
``````

PS: It is a bad idea to start your programming experience with JavaScript. The problem is that the language does NOT help a programmer/developer learn how to properly implement an algorithm because it attempts to correct the programmer/developer wrong logic/syntax. If you want to start your programming experience, start with either lower level language as C or C++ or a bit higher level language as Java (not the same as JavaScript), python, small talk, or ruby (not perl because the language is a bit messy).

PSS: The level of language does not mean its difficulty but rather the ability to access the computer/operating system functionality/hardware it is running on.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.