2D Arrays in Javascript - javascript

For college, we have a problem to solve regarding 2D arrays, however the nature of them has never been cover in class. I've scoured this site for answers(which might be evident in my code) but cannot get it to work, or even truly understand what is going on or why. The exact question is:
Write a program that utilises a 8x8 2-dimensional array.
(a) Initialise the array elements via nested for loops as follows
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
...
...
57 58 59 60 61 62 63 64
(b) Add some code that will display all array elements in an 8x8 HTML table.
(c) Use nested for loops for calculating the sum and the average of the
values stored in the array.
Let a function display these values on screen eg use alert().
The code I have so far is :
x = matrix( 8 , 8, 0 ); // 8 lines, 8 cols filled with empty string
function matrix( rows, cols, defaultValue){
var arr = [];
// Creates all lines:
for(var i=0; i < rows; i++){
var add = 1
// Creates an empty line
arr.push([]);
// Adds cols to the empty line:
arr[i].push( new Array(cols));
for(var j=0; j < cols; j++){
// Initializes:
arr[i][j] = defaultValue + add;
}
var add = add + 1
}
return arr;
}
function displayInDiv() {
var output_string_ = "" ;
var lastElement = 64 ;
output_string_ = output_string_
+'<table>'
+'<tr>'
+'<th width="11%" align="left">ARRAY INDEX</th>'
+'<th width="11%" align="right"> array_1</th>'
+'<th width="11%" align="right"> array_2</th>'
+'<th width="11%" align="right"> array_3</th>'
+'<th width="11%" align="right"> array_4</th>'
+'<th width="11%" align="right"> array_5</th>'
+'<th width="11%" align="right"> array_6</th>'
+'<th width="11%" align="right"> array_7</th>'
+'<th width="11%" align="right"> array_8</th>'
+'</tr>'
;
for ( var i = 1 ; i < 9 ; i++ ) {
for ( var j = 0 ; j < 7 ; j++ ) {
output_string_ = output_string_
+'<tr id="table_row_'
+ i
+'">'
+'<td width="11%" align="left">'
+'['
+ i
+']'
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'<td width="11%" align="right">'
+ Array[i][j]
+'</td>'
+'</tr>'
;
}
output_string_ = output_string_
+'<table>'
;
var output_section_ = document.getElementById("list_");
output_section_.innerHTML = output_string_ ;
}
}
Sorry for the huge text dump, but i'm completely stumped. Any help would be greatly appreciated.

I believe the exact code you're looking for is this
var outer = new Array();
for(var i = 0; i < 8; i++) {
var inner = new Array
for(var j = 0; j < 8; j++) {
inner[j] = (i * 8) + j + 1;
}
outer[i] = inner;
}
console.log(outer);
A 2D array is just an array of arrays, here I labelled them inner and outer.
There are 8 inner arrays of length 8, giving you 64 total entries. The value of each entry is 8 * the outer index (which starts at 0), plus the inner index plus 1 (because it also starts at 0).
This should give you enough information to answer parts b and c yourself, but feel free to comment below if you'd like further help. :)

answer for (a)
var arr = [];
var value = 0;
for(var i = 0; i < 8; i++){
var tempArr = [];
for(var j = 0; j < 8; j++){
tempArr.push(++value);
}
arr.push(tempArr);
}
//`arr` has values initialized with 1 - 64
answer for (b)
var table = "<table>";
for(var i = 0; i < 8; i++){
table += "<tr>";
for(var j = 0; j < 8; j++){
table += "<td>" + arr[i][j] + "</td>";
}
table += "</tr>";
}
table += "</table>";
//assume you have an element with id="tbl" in DOM
document.getElementById("tbl").innerHtml = table;
answer for (c)
var sum = 0 , avg = 0;
for(var i = 0; i < 8; i++){
for(var j = 0; j < 8; j++){
sum += arr[i][j];
}
}
avg = sum / 64;
alert("sum: " + sum + " Average: " + avg);

After you create array you can initialize each of the element with another array.
var myarray=new Array(8)
for (i=0; i <8; i++)
myarray[i]=new Array(8)
Hope this helps.
Cheers !

I made a JSFiddle for this, with comments.
HTML
<button onclick="showCalculations();">Show Calculations!</button>
<div id="container"></div>
JavaScript
//Create the 2-d array
var rows = 8; //Number of rows
var columns = 8; //Number of columns
var list = []; //Array where we will put the data
var index = 0; //Keeps track of which index we're at
for(var i = 0; i < rows; i++){
var rowList = []; //Create sub-array
list.push(rowList); //Add the sub-array to our top-level array
for(var y = 0; y < columns; y++){
index++; //Increment the index
rowList.push(index); //Add the index to the current sub-array
}
}
//Create the Table as HTML string
var table = "<table>"; //Start HTML for table
for(var i = 0; i < list.length; i++){
var row = list[i];
table += "<tr>"; //Start HTML for row
for(var y = 0; y < row.length; y++){
var column = row[y];
table += "<td>" + column + "</td>"; //Table cell with content
}
table += "</tr>"; //End HTML for row
}
table += "</table>"; //End HTML for table
document.getElementById("container").innerHTML = table; //Find element with id container and set HTML to table
//Calculations
var sum = 0; //Keeps track of the sum
var numberOfNumbers = 0; //Keeps track of how many numbers has been summed
for(var i = 0; i < list.length; i++){
var row = list[i];
for(var y = 0; y < row.length; y++){
var column = row[y];
sum += column; //Add to sum
numberOfNumbers++; //Increment amount of numbers
}
}
var avarage = sum / numberOfNumbers; //Calculate avarage
//Function to alert the values
function showCalculations(){
alert("Sum: " + sum + "\nAvarage: " + avarage)
}
Note that the creation of the Table and the calculations can be done in the same for-loop. (Acctually all can be, but then we're not making use of the Array we create).

I correct your code. Html:
<button onclick='run()'>Show</button>
<div id='list_'></div>
And js:
function run() {
x = matrix( 8 , 8, 0 );
alert(x);
displayInDiv(x);
}
function matrix( rows, cols, defaultValue){
var arr = [];
var number = 1;
for(var i = 0; i < rows; i++){
arr.push([]);
arr[i].push( new Array(cols));
for(var j=0; j < cols; j++){
arr[i][j] = number;
number++;
}
}
return arr;
}
function displayInDiv() {
var output_string_ = "" ;
var lastElement = 64 ;
var output_string_ = '<table>'
for ( var i = 0 ; i < 8 ; i++ ) {
output_string_ += "<tr id='table_row_" + i + "'>";
for ( var j = 0 ; j < 8 ; j++ ) {
output_string_ += '<td width="11%" align="left">' + x[i][j] + '</td>';
}
output_string_ += '</tr>';
}
output_string_ += '</table>';
var output_section_ = document.getElementById("list_");
output_section_.innerHTML = output_string_ ;
}

var num;
var arr = [];
// This for loop populates the array
for (var i = 0; i <= 7; i++) {
arr[i] = [];
for (var j = 0; j <= 7; j++) {
arr[i][j] = i * 8 + j + 1;
}
}
// This function displays the populated array
function displayArr(arr) {
var container = document.getElementById("container");
var append = "<table>";
for (var i = 0; i < arr.length; i++) {
append += "<tr>";
for (var j = 0; j < arr[i].length; j++) {
num = i * 8 + j + 1;
append += "<td>" + num + "</td>";
}
append += "</tr>";
}
container.innerHTML = append;
}
// Alerts the sum of all numbers in the 2d array
function getSum() {
var sum = 0;
for (var i = 0; i <= 7; i++) {
for (var j = 0; j <= 7; j++) {
sum += i * 8 + j + 1;
}
}
return sum;
}
// Alerts the average of all numbers in the 2d array
function getAvg() {
var totalNumbers = 0;
var avg = 0;
for (var i = 0; i <= 7; i++) {
for (var j = 0; j <= 7; j++) {
totalNumbers++;
}
}
return getSum() / totalNumbers;
}
alert(getAvg());
alert(getSum());
displayArr(arr);
<section id="container"></section>
EDIT* Added the average and sum functions

Related

How can I create a Table in JS with "for loops" filled with numbers 1 to 100

I created multiplication table using for loop
now I need to create the same table with numbers 1 to 100 like this one:[table][1]
how do I create this one
[1]: https://i.stack.imgur.com/FAacu.png
document.write('<table border="3">');
for (var x = 1; x < 11; x++) {
document.write("<tr>")
for (let i = 1; i < 11; i++) {
document.write("<td>" + x * i + "</td>")
}
document.write("</td>")
}
document.write("</table>")
You can start x from 0 (to 10) then the formula of the current cell's number is x * 10 + i so for [2,2] cell it would be 1 * 10 + 2
document.write('<table border="3">');
for (let x = 0; x < 10; x++) {
document.write("<tr>")
for (let i = 1; i <= 10; i++) {
document.write("<td>" + (x * 10 + i) + "</td>")
}
document.write("</td>")
}
document.write("</table>")
I have looked into your code and seems like logic inside your for loop is not correct.
I am posting a working code logic for this, I hope this is what you need.
document.write('<table border="3">');
for (var x = 1; x <= 100; x += 10) {
document.write("<tr>");
for (let i = x; i <= x + 9; i++) {
document.write("<td>" + i + "</td>");
}
document.write("</td>");
}
document.write("</table>");

Building a JavaScript grid with odd and even characters using two loops

This is my first question on StackOverflow.
I have to build gridGenerator(num). If num is 3, it would look like this:
#_#
_#_
#_#
If num is 4, it would look like this:
#_#_
_#_#
#_#_
_#_#
I was able to solve it for odd numbers, but struggle to adjust it to even numbers.
function gridGenerator(num) {
var grid = '';
var row = '';
for (var i = 0; i < num; i++) {
for (var j = 0; j < num; j++) {
if (row.length % 2) {
row += '_';
} else {
row += '#';
}
}
grid += row.slice(-num) + '\n';
}
return grid;
}
console.log(gridGenerator(3));
Need a hint how to solve it for 2, 4, and other even numbers. Thank you!
Try this
if ((i+j) % 2)
function gridGenerator(num) {
var grid = '';
var row = '';
for (var i = 0; i < num; i++) {
for (var j = 0; j < num; j++) {
if ((i+j) % 2) {
row += '_';
} else {
row += '#';
}
}
grid += row.slice(-num) + '\n';
}
return grid;
}
console.log(gridGenerator(4));
You can use the condition num % 2 to determine if a number is even or odd. I would use two loops like you are doing. Make your character addition based on the even / odd state of the row and column. At the end of each row insert the line break.
EDIT: Here you go.
function generateGrid( num ) {
let i, j, grid = "";
for ( i = 0; i < num; i++ ) {
for ( j = 0; j < num; j++ ) {
if ( ( i + j ) % 2 ) {
grid += "_";
} else {
grid += "#";
}
}
grid += "\n";
}
return grid;
}
var grid = generateGrid( 4 );
console.log( grid );
function gridGen(num) {
var even = '';
for (var i = 0; i< num ; i++)
even += (i%2) ? '_' : '#';
odd = even.substring(1) + (num%2 ? '_' : '#');
var out = '';
for (var i = 0; i< num ; i++)
out += ((i%2) ? odd : even) + '\n';
return out;
}
console.log('Even Case');
console.log( gridGen(8));
console.log('Odd Case');
console.log( gridGen(7));
If you are looking for another approach + efficiency try this

Javascript - write duplicates in array to html

I need to write a function that creates an array of random numbers between 1 and 20 and prints each number in a table. If it's a duplicate of a number that has already been generated, it needs to be highlighted in red.
My issue is that after the first duplicate has been printed in red, if there is another, it would not be printed in red. I can't get it to work for more than one time.
Here's the output:
Here's my code:
function randomNumberTable(){
// create array with random numbers
var nums = new Array();
for(var i = 0; i < 10; i++){
nums[i] = randomNumber();
}
// create header row
document.writeln("<table border = \"1\">");
document.writeln("<th>Index</th>");
document.writeln("<th>Number</th>");
// if duplicate, print in red, else, black
for(var j = 0; j <= nums.length-1; j++){
var isExist = numberExists(nums[j], nums, j);
if (isExist){
document.writeln("<tr>");
document.writeln("<td>" + j + "</td>");
document.writeln("<td><font color=\"red\">" + nums[j] + "</font></td>");
document.writeln("</tr>");
}
else{
document.writeln("<tr>");
document.writeln("<td>" + j + "</td>");
document.writeln("<td>" + nums[j] + "</td>");
document.writeln("</tr>");
}
}
}
// generate a random number between 1 and 20
function randomNumber(){
var randomNum = Math.floor(Math.random()*20) + 1;
return randomNum;
}
// checking if the number exists
function numberExists(num, myArray, myIndex){
for(var k = 0; k < myIndex; k++){
if(num == myArray[k])
return true;
else
return false;
}
}
change your numberExists function like this.
function numberExists(num, myArray, myIndex){
for(var k = 0; k < myIndex; k++){
if(num == myArray[k])
return true;
}
return false;
}

Having issues with clearing area around blank squares in minesweeper

Ok i finally got my minesweeper game made just needing one more thing if anyone could help me with. The part when you click on an unnumbered square and it will reveal some of the board. I have been playing around on this for sometime just drawing a blank. This is a simple minesweeper game just in java script. I have everything labeled where things should go to make it easier to find and i will bold it on where my code ive been working on is.
//Global
//store the value of each square
var gaValue = new Array(8)
for (i = 0; i <= 8; i++)
gaValue[i] = new Array(8)
for (i = 0; i <= 8; i++)
{
//loop through each item in those row
for (j = 0; j <= 8 ; j++)
gaValue[i][j] = 0
}
//Store the status of each square
var gaSquare = new Array(8)
for (j = 0; j <= 8; j++)
gaSquare[j] = new Array(8)
for (j = 0; j <= 8; j++)
{
//loop through each item in those row
for (i = 0; i <= 8 ; i++)
gaSquare[i][j] = "C"
}
//Track of whether the game is over or not (starts this with false)
var gbGameOver = false
function vInit()
{
var strHTML
var i
var j
strHTML = "<table style='margin-left:auto;margin-right:auto'>"
strHTML += "<tr><td colspan='8' style='text-align:center'>MineSweeper</td></tr>"
strHTML += "<tr><td colspan='8' style='text-align:center'><input type='button' id='btnNew' value='New Game' onclick='vNewGame()'></td></tr>"
//Loop through the rows to build the table of tiles
for (i = 0; i < 8; i++)
{
strHTML += "<tr>"
for (j = 0; j < 8; j++)
strHTML += '<td><img src="images/sqt0.png" id="square' + i + ', ' + j + '" onclick="vClick(' + i + ', ' + j + ')"/></td>';
strHTML += "<tr>";
}
strHTML += '<tr><td colspan="8" style="text-align:center"><textarea id="taOut" cols="18" rows="10"></textarea></td></tr>'
strHTML += "</table>"
frmGrid.innerHTML = strHTML
//Place bombs
var iBomb = 0
var iRow = Math.floor(Math.random() * 8)
var iCol = Math.floor(Math.random() * 8)
while (iBomb < 8)
{
while (gaValue[iRow][iCol] == 9)
{
iRow = Math.floor(Math.random() * 8)
iCol = Math.floor(Math.random() * 8)
}
gaValue[iRow][iCol] = 9
iBomb++
}
//Calculate clue values around mines
var iMine = 0
for (i = 0; i < 8; i++)
{
for (j = 0; j < 8; j++)
{
for (k = (i - 1) ; k <= (i + 1) ; k++)
for (m = (j - 1) ; m <= (j + 1) ; m++)
if (k >= 0 && k <= 9 && j >= 0 && j <= 9)
if (gaValue[k][m] == 9)
iMine++
if (gaValue[i][j] != 9)
gaValue[i][j] = iMine
iMine = 0
}
}
}
//Get the ID of the image I need to change
function vClick(iRow, iCol)
{
var gaSquare = "square" + iRow + ", " + iCol
var strOut = ""
gaSquare[iRow][iCol] = 'o';
document.getElementById(gaSquare).src = "images/" + gaValue[iRow][iCol] + ".png"
if (gaValue[iRow][iCol] == 9)
{
gbGameOver = true
strOut = "Game Over"
vOver()
}
else if (gaValue[iRow][iCol] == 0)
vZero(iRow, iCol)
document.getElementById('taOut').value = strOut
}
//GameOver
function vOver()
{
var i
var j
var strID;
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++) {
strID = "square" + i + ", " + j;
document.getElementById(strID).src = "images/" + gaValue[i][j] + ".png"
}
}
**//Clearing area
function vZero(iRow, iCol, i, j) {
for (i = iRow - 1; i <= iRow + 1; i++) {
for (j = iCol - 1; j <= iCol + 1; j++) {
if (k >= 0 && k <= 8 && j >= 0 && j <= 8)
vClick(i, j)
}**
//Start new game
function vNewGame() {
vInit()
}
//no menu on right click
function bIsRightButtonClicked(e) {
var rightclick = false
e = e || window.event
if (e.which) {
rightclick = (e.which == 3)
}
else if (e.button) {
rightclick = (e.button == 2)
}
return rightclick
}
}
}
I believe the main mistake is that you are referring to k inside vZero() when that variable is not defined. You also appear to be missing a closing curly bracket or two on that function.
Try changing that function to as follows:
//Clearing area
function vZero(iRow, iCol) {
for (var i = iRow - 1; i <= iRow + 1; i++) {
for (var j = iCol - 1; j <= iCol + 1; j++) {
if (i >= 0 && i <= 8 && j >= 0 && j <= 8) vClick(i, j);
}
}
}
You'll note that I changed the i and j parameters to be local variables, because they are only used by that function for the purposes of the for loops. You don't need to have them as parameters. Doing so only confuses other developers because that implies that you need to pass a value for them into the function for it to work, whereas you only need to pass in iRow and iCol. Does that make sense?

changing 2 random numbers in 30 times in number table using java script

In this code each time you open the html page two random numbers are generated and thier location in the matrix will be changed.
for example the random numbers are 2,8
in the main table 2 is in the matrix[0][1],matrix[1][7],matrix[2][4],matrix[3][0],matrix[4][6],matrix[5][3],matrix[6][8],matrix[3][0],matrix[7][5]
,matrix[8][2] .in the result table 8 is set in these location and 2 is set in the current locations of 8.
I want to repeat this, 30 times.
so far I have :
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<body>
<script type="text/javascript">
var matrix = new Array();
matrix[0]=[1,2,3,4,5,6,7,8,9];
matrix[1]=[4,5,6,7,8,9,1,2,3];
matrix[2]=[7,8,9,1,2,3,4,5,6];
matrix[3]=[2,3,4,5,6,7,8,9,1];
matrix[4]=[5,6,7,8,9,1,2,3,4];
matrix[5]=[8,9,1,2,3,4,5,6,7];
matrix[6]=[3,4,5,6,7,8,9,1,2];
matrix[7]=[6,7,8,9,1,2,3,4,5];
matrix[8]=[9,1,2,3,4,5,6,7,8];
document.writeln('<table border="1">');
for (i = 0; i < 9; i++)
{
document.writeln('<tr>');
for (j = 0; j < 9; j++)
document.writeln('<td>' + matrix[i][j] + '</td>');
document.writeln('</tr>');
}
document.writeln('</table>');
document.writeln('<table border="1">');
document.writeln("The random numbers are:");
document.writeln('<br>');
var r1 = Math.ceil(Math.random() * 9);
var r2 = Math.ceil(Math.random() * 9);
document.writeln(r1);
document.writeln(r2);
document.writeln('<br>');
document.writeln("The result table is:");
for(i=0; i<9; i++)
{
document.writeln('<tr>');
for(j=0; j<9; j++)
{
if(matrix[i][j]==r1)
{
matrix[i][j]=r2;
document.writeln('<td>' + matrix[i][j] + '</td>');
}
else if(matrix[i][j]!=r1 && matrix[i][j]!=r2)
document.writeln('<td>' + matrix[i][j] + '</td>');
else if(matrix[i][j]==r2)
{
matrix[i][j]=r1;
document.writeln('<td>' + matrix[i][j] + '</td>');
}
}
document.writeln('</tr>');
}
document.writeln('</table>');
</script>
</body>
</html>
I would change your code slightly.
First, I'd make a method to print the table:
function printMatrix(var matrix)
{
document.writeln('<table border="1">');
for (i = 0; i < 9; i++)
{
document.writeln('<tr>');
for (j = 0; j < 9; j++)
document.writeln('<td>' + matrix[i][j] + '</td>');
document.writeln('</tr>');
}
document.writeln('</table>');
}
Then, I'd make a method for the swapping:
function sawpTwoNumbers(matrix)
{
document.writeln("The random numbers are:");
document.writeln('<br>');
var r1 = Math.ceil(Math.random() * 9);
var r2 = Math.ceil(Math.random() * 9);
document.writeln(r1);
document.writeln(r2);
document.writeln('<br>');
// This is new code:
for(int i=0; i< matrix.length; i++){
var r1Index = matrix[i].indexOf(r1);
var r2Index = matrix[i].indexOf(r2);
matrix[i][r1Index] = r2;
matrix[i][r2Index] = r1;
}
}
Next, I'd put your code in the pageLoad method:
function pageLoad()
{
var matrix = new Array();
matrix[0]=[1,2,3,4,5,6,7,8,9];
matrix[1]=[4,5,6,7,8,9,1,2,3];
matrix[2]=[7,8,9,1,2,3,4,5,6];
matrix[3]=[2,3,4,5,6,7,8,9,1];
matrix[4]=[5,6,7,8,9,1,2,3,4];
matrix[5]=[8,9,1,2,3,4,5,6,7];
matrix[6]=[3,4,5,6,7,8,9,1,2];
matrix[7]=[6,7,8,9,1,2,3,4,5];
matrix[8]=[9,1,2,3,4,5,6,7,8];
printMatrix(matrix);
// This is new code:
// It will call the swap method and the print method 30 times.
for(int i = 0; i < 30; i++)
{
swapTwoNumbers(matrix);
printMatrix(matrix);
}
}
Please Note: I haven't tested this code. I don't guarantee that it works. I hope it'll give you a push in the right direction though.

Categories

Resources