Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would change your code slightly.</p> <p>First, I'd make a method to print the table:</p> <pre><code>function printMatrix(var matrix) { document.writeln('&lt;table border="1"&gt;'); for (i = 0; i &lt; 9; i++) { document.writeln('&lt;tr&gt;'); for (j = 0; j &lt; 9; j++) document.writeln('&lt;td&gt;' + matrix[i][j] + '&lt;/td&gt;'); document.writeln('&lt;/tr&gt;'); } document.writeln('&lt;/table&gt;'); } </code></pre> <p>Then, I'd make a method for the swapping:</p> <pre><code>function sawpTwoNumbers(matrix) { document.writeln("The random numbers are:"); document.writeln('&lt;br&gt;'); var r1 = Math.ceil(Math.random() * 9); var r2 = Math.ceil(Math.random() * 9); document.writeln(r1); document.writeln(r2); document.writeln('&lt;br&gt;'); // This is new code: for(int i=0; i&lt; matrix.length; i++){ var r1Index = matrix[i].indexOf(r1); var r2Index = matrix[i].indexOf(r2); matrix[i][r1Index] = r2; matrix[i][r2Index] = r1; } } </code></pre> <p>Next, I'd put your code in the pageLoad method:</p> <pre><code>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 &lt; 30; i++) { swapTwoNumbers(matrix); printMatrix(matrix); } } </code></pre> <p><strong>Please Note:</strong> 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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload