2018-10-10 18:03:03 -04:00
---
id: 5a23c84252665b21eecc7eb1
2021-02-06 04:42:36 +00:00
title: Identity matrix
2018-10-10 18:03:03 -04:00
challengeType: 5
2021-02-06 04:42:36 +00:00
forumTopicId: 302290
2021-01-13 03:31:00 +01:00
dashedName: identity-matrix
2018-10-10 18:03:03 -04:00
---
2020-12-16 00:37:30 -07:00
# --description--
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
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).
< ul >
< li style = 'list-style: none;' > \(\displaystyle I_{n}=\begin{bmatrix} 1 & #x26 ; 0 & #x26 ; 0 \cr 0 & #x26 ; 1 & #x26 ; 0 \cr 0 & #x26 ; 0 & #x26 ; 1 \cr \end{bmatrix}\)</ li >
< / ul >
# --instructions--
Write a function that takes a number `n` as a parameter and returns the identity matrix of order \\( n \\times n \\).
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
# --hints--
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
`idMatrix` should be a function.
2018-10-10 18:03:03 -04:00
```js
2020-12-16 00:37:30 -07:00
assert(typeof idMatrix == 'function');
```
2021-02-06 04:42:36 +00:00
`idMatrix(1)` should return an array.
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
```js
assert(Array.isArray(idMatrix(1)));
2018-10-10 18:03:03 -04:00
```
2021-02-06 04:42:36 +00:00
`idMatrix(1)` should return `[ [ 1 ] ]` .
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
```js
assert.deepEqual(idMatrix(1), results[0]);
```
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
`idMatrix(2)` should return `[ [ 1, 0 ], [ 0, 1 ] ]` .
2018-10-10 18:03:03 -04:00
```js
2020-12-16 00:37:30 -07:00
assert.deepEqual(idMatrix(2), results[1]);
2018-10-10 18:03:03 -04:00
```
2021-02-06 04:42:36 +00:00
`idMatrix(3)` should return `[ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ]` .
2018-10-10 18:03:03 -04:00
2020-12-16 00:37:30 -07:00
```js
assert.deepEqual(idMatrix(3), results[2]);
```
2018-10-10 18:03:03 -04:00
2021-02-06 04:42:36 +00:00
`idMatrix(4)` should return `[ [ 1, 0, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ] ]` .
2018-10-10 18:03:03 -04:00
```js
2020-12-16 00:37:30 -07:00
assert.deepEqual(idMatrix(4), results[3]);
2018-10-10 18:03:03 -04:00
```
2020-08-13 17:24:35 +02:00
2021-01-13 03:31:00 +01:00
# --seed--
## --after-user-code--
```js
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 ] ]]
```
## --seed-contents--
```js
function idMatrix(n) {
}
```
2020-12-16 00:37:30 -07:00
# --solutions--
2021-01-13 03:31:00 +01:00
```js
function idMatrix(n) {
return Array.apply(null, new Array(n)).map(function (x, i, xs) {
return xs.map(function (_, k) {
return i === k ? 1 : 0;
})
});
}
```