2018-10-04 14:37:37 +01:00
---
id: 5a23c84252665b21eecc7eb1
2020-11-27 19:02:05 +01:00
title: Identity matrix
2018-10-04 14:37:37 +01:00
challengeType: 5
2019-08-05 09:17:33 -07:00
forumTopicId: 302290
2018-10-04 14:37:37 +01:00
---
2020-11-27 19:02:05 +01: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 14:18:18 +09:00
< ul >
2020-11-27 19:02:05 +01:00
< 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 >
2019-03-06 14:18:18 +09:00
< / ul >
2018-10-04 14:37:37 +01:00
2020-11-27 19:02:05 +01: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 14:37:37 +01:00
```
2020-11-27 19:02:05 +01:00
`idMatrix(1)` should return an array.
2018-10-04 14:37:37 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(Array.isArray(idMatrix(1)));
```
2018-10-04 14:37:37 +01:00
2020-11-27 19:02:05 +01:00
`idMatrix(1)` should return `[ [ 1 ] ]` .
2018-10-04 14:37:37 +01:00
```js
2020-11-27 19:02:05 +01:00
assert.deepEqual(idMatrix(1), results[0]);
```
2020-09-15 09:57:40 -07:00
2020-11-27 19:02:05 +01:00
`idMatrix(2)` should return `[ [ 1, 0 ], [ 0, 1 ] ]` .
```js
assert.deepEqual(idMatrix(2), results[1]);
2018-10-04 14:37:37 +01:00
```
2020-11-27 19:02:05 +01: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 14:37:37 +01:00
2020-11-27 19:02:05 +01:00
# --seed--
2018-10-04 14:37:37 +01:00
2020-11-27 19:02:05 +01:00
## --after-user-code--
2018-10-04 14:37:37 +01:00
```js
2018-10-20 21:02:47 +03: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 14:37:37 +01:00
```
2020-11-27 19:02:05 +01:00
## --seed-contents--
2018-10-04 14:37:37 +01:00
2020-11-27 19:02:05 +01:00
```js
function idMatrix(n) {
2018-10-04 14:37:37 +01:00
2020-11-27 19:02:05 +01:00
}
```
2018-10-04 14:37:37 +01:00
2020-11-27 19:02:05 +01:00
# --solutions--
2018-10-04 14:37:37 +01:00
```js
2019-03-06 14:18:18 +09:00
function idMatrix(n) {
2020-11-27 19:02:05 +01: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 14:37:37 +01:00
}
```