We have been given an assignment to create a 3x3 matrix using input boxes and make a code to check if the given numbers add up correctly to make is a magic square. No prompt boxes and for us to use an array to accomplish the task. I have used input boxes to get values before using the "document.myform....value" method, but I have no idea how to implement that with an array.
This is what I have so far:
function myArray() {
var matrix = new Array[];
for (var i = 0; i < 3; i++) {
matrix[i] = new Array(3)
}
enterValues();
}
function enterNum() {
for (var row = 0; row < 3; row++) {
for (var col = 0; col < 3; col++)
matrix[row][col].innerHTML;
}
}
function magicSquare() {
var magSqu = false;
var sum = 0;
for (var col = 0; col < 3; col++) {
sum = sum + matrix[0][col];
}
var rowSum = 0;
for (var i = 1; i < 3; i++) {
for (var j = 0; j < 3; j++) {
rowSum = rowSum + matrix[i][j];
if (rowSum != sum) {
magSqu = false;
break;
}
}
}
var sum_diagonal = 0;
if (magSqu) {
for (var i = 0; i < 3; i++)
for (var j = 0; j < 3; j++)
if (i == j)
sum_diagonal += matrix[i][j];
if (sum_diagonal != sum) {
magSqu = false;
}
}
if (magSqu) {
sum_diagonal = 0;
for (var i = 0; i < 3; i++)
for (var j = 0; j < 3; j++)
if ((i + j) == 2)
sum_diagonal += matrix[i][j];
if (sum_diagonal != sum) {
magSqu = false;
}
}
if (magSqu == true) {
document.getElementById("result").innerHTML = "This is a magic square.";
} else {
document.getElementById("result").innerHTML = "This is not a magic square.";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Magic Square</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<table border='1'>
<tbody>
<tr>
<td id="r1c1"><input type="text" name="inp11"></td>
<td id="r1c2"><input type="text" name="inp12"></td>
<td id="r1c3"><input type="text" name="inp13"></td>
</tr>
<tr>
<td id="r2c1"><input type="text" name="inp21"></td>
<td id="r2c2"><input type="text" name="inp22"></td>
<td id="r2c3"><input type="text" name="inp23"></td>
</tr>
<tr>
<td id="r3c1"><input type="text" name="inp31"></td>
<td id="r3c2"><input type="text" name="inp32"></td>
<td id="r3c3"><input type="text" name="inp33"></td>
</tr>
</tbody>
</table>
<input type="submit" id="magicButton" value="Compute Score" onclick="magicSquare();">
<div id="result"> </div>
</body>
</html>
Where am I going wrong with this?