2018-10-04 13:37:37 +00:00
---
id: 5a23c84252665b21eecc7eb1
2020-11-27 18:02:05 +00:00
title: Identity matrix
2018-10-04 13:37:37 +00:00
challengeType: 5
2019-08-05 16:17:33 +00:00
forumTopicId: 302290
2021-01-13 02:31:00 +00:00
dashedName: identity-matrix
2018-10-04 13:37:37 +00:00
---
2020-11-27 18:02:05 +00:00
# --description--
An *identity matrix* is a square matrix of size \\( n \\times n \\), where the diagonal elements are all `1` s (ones), and all the other elements are all `0` s (zeroes).
2019-03-06 05:18:18 +00:00
< ul >
2020-11-27 18:02:05 +00:00
< li style = 'list-style: none;' > \(\displaystyle I_{n}=\begin{bmatrix} 1 & 0 & 0 \cr 0 & 1 & 0 \cr 0 & 0 & 1 \cr \end{bmatrix}\)</ li >
2019-03-06 05:18:18 +00:00
< / ul >
2018-10-04 13:37:37 +00:00
2020-11-27 18:02:05 +00:00
# --instructions--
Write a function that takes a number `n` as a parameter and returns the identity matrix of order \\( n \\times n \\).
# --hints--
`idMatrix` should be a function.
```js
assert(typeof idMatrix == 'function');
2018-10-04 13:37:37 +00:00
```
2020-11-27 18:02:05 +00:00
`idMatrix(1)` should return an array.
2018-10-04 13:37:37 +00:00
2020-11-27 18:02:05 +00:00
```js
assert(Array.isArray(idMatrix(1)));
```
2018-10-04 13:37:37 +00:00
2020-11-27 18:02:05 +00:00
`idMatrix(1)` should return `[ [ 1 ] ]` .
2018-10-04 13:37:37 +00:00
```js
2020-11-27 18:02:05 +00:00
assert.deepEqual(idMatrix(1), results[0]);
```
2020-09-15 16:57:40 +00:00
2020-11-27 18:02:05 +00:00
`idMatrix(2)` should return `[ [ 1, 0 ], [ 0, 1 ] ]` .
```js
assert.deepEqual(idMatrix(2), results[1]);
2018-10-04 13:37:37 +00:00
```
2020-11-27 18:02:05 +00:00
`idMatrix(3)` should return `[ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ]` .
```js
assert.deepEqual(idMatrix(3), results[2]);
```
`idMatrix(4)` should return `[ [ 1, 0, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ] ]` .
```js
assert.deepEqual(idMatrix(4), results[3]);
```
2018-10-04 13:37:37 +00:00
2020-11-27 18:02:05 +00:00
# --seed--
2018-10-04 13:37:37 +00:00
2020-11-27 18:02:05 +00:00
## --after-user-code--
2018-10-04 13:37:37 +00:00
```js
2018-10-20 18:02:47 +00:00
let results=[[ [ 1 ] ],
[ [ 1, 0 ], [ 0, 1 ] ],
[ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ],
[ [ 1, 0, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ] ]]
2018-10-04 13:37:37 +00:00
```
2020-11-27 18:02:05 +00:00
## --seed-contents--
2018-10-04 13:37:37 +00:00
2020-11-27 18:02:05 +00:00
```js
function idMatrix(n) {
2018-10-04 13:37:37 +00:00
2020-11-27 18:02:05 +00:00
}
```
2018-10-04 13:37:37 +00:00
2020-11-27 18:02:05 +00:00
# --solutions--
2018-10-04 13:37:37 +00:00
```js
2019-03-06 05:18:18 +00:00
function idMatrix(n) {
2020-11-27 18:02:05 +00:00
return Array.apply(null, new Array(n)).map(function (x, i, xs) {
return xs.map(function (_, k) {
return i === k ? 1 : 0;
})
});
2018-10-04 13:37:37 +00:00
}
```