Created
February 15, 2018 07:30
-
-
Save ahrjarrett/326554ad50e09c7306c1a479fcc66a16 to your computer and use it in GitHub Desktop.
Let's create and print a 3x3 matrix in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // p. 55: learning js data structures & algorithms, 2nd ed. | |
| // Let's create a 3 x 3 matrix: | |
| let matrix3x = []; | |
| for (let i = 0; i < 3; i++) { | |
| matrix3x[i] = []; | |
| for (let j = 0; j < 3; j++) { | |
| matrix3x[i][j] = []; | |
| for (let z = 0; z < 3; z++) { | |
| matrix3x[i][j][z] = i + j + z; | |
| } | |
| } | |
| } | |
| console.log(matrix3x); /* => | |
| [ [ [ 0, 1, 2 ], [ 1, 2, 3 ], [ 2, 3, 4 ] ], | |
| [ [ 1, 2, 3 ], [ 2, 3, 4 ], [ 3, 4, 5 ] ], | |
| [ [ 2, 3, 4 ], [ 3, 4, 5 ], [ 4, 5, 6 ] ] ] */ | |
| // To output the content of this matrix, we can use the following code: | |
| for (let i = 0; i < matrix3x.length; i++) { | |
| for (let j = 0; j < matrix3x[i].length; j++) { | |
| for (let z = 0; z < matrix3x[i][j].length; z++) { | |
| console.log(matrix3x[i][j][z]); | |
| } | |
| } | |
| } | |
| /* => | |
| 0 | |
| 1 | |
| 2 | |
| 1 | |
| 2 | |
| 3 | |
| 2 | |
| 3 | |
| 4 | |
| 1 | |
| 2 | |
| 3 | |
| 2 | |
| 3 | |
| 4 | |
| 3 | |
| 4 | |
| 5 | |
| 2 | |
| 3 | |
| 4 | |
| 3 | |
| 4 | |
| 5 | |
| 4 | |
| 5 | |
| 6 | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment