2018-10-04 13:37:37 +00:00
---
title: Identity matrix
id: 5a23c84252665b21eecc7eb1
challengeType: 5
---
## Description
< section id = 'description' >
2019-06-14 11:04:16 +00:00
An < i > identity matrix</ i > is a square matrix of size \( n \times n \), where the diagonal elements are all < code > 1</ code > s (ones), and all the other elements are all < code > 0</ code > s (zeroes).
2019-03-06 05:18:18 +00:00
< ul >
< 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 >
< / ul >
2018-10-04 13:37:37 +00:00
< / section >
## Instructions
< section id = 'instructions' >
2019-03-06 05:18:18 +00:00
Write a function that takes a number < code > n</ code > as a parameter and returns the identity matrix of order \( n \times n \).
2018-10-04 13:37:37 +00:00
< / section >
## Tests
< section id = 'tests' >
```yml
tests:
2018-10-08 11:52:10 +00:00
- text: < code > idMatrix</ code > should be a function.
2019-07-26 12:24:52 +00:00
testString: assert(typeof idMatrix=='function');
2018-10-08 11:52:10 +00:00
- text: < code > idMatrix(1)</ code > should return an array.
2019-07-26 12:24:52 +00:00
testString: assert(Array.isArray(idMatrix(1)));
2019-03-06 05:18:18 +00:00
- text: < code > idMatrix(1)</ code > should return < code > [ [ 1 ] ]</ code > .
testString: assert.deepEqual(idMatrix(1),results[0]);
- text: < code > idMatrix(2)</ code > should return < code > [ [ 1, 0 ], [ 0, 1 ] ]</ code > .
testString: assert.deepEqual(idMatrix(2),results[1]);
- text: < code > idMatrix(3)</ code > should return < code > [ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ]</ code > .
testString: assert.deepEqual(idMatrix(3),results[2]);
- text: < code > idMatrix(4)</ code > should return < code > [ [ 1, 0, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ] ]</ code > .
testString: assert.deepEqual(idMatrix(4),results[3]);
2018-10-04 13:37:37 +00:00
```
< / section >
## Challenge Seed
< section id = 'challengeSeed' >
< div id = 'js-seed' >
```js
2019-03-06 05:18:18 +00:00
function idMatrix(n) {
2018-10-04 13:37:37 +00:00
// Good luck!
}
```
< / div >
### After Test
< div id = 'js-teardown' >
```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
```
< / div >
< / section >
## Solution
< section id = 'solution' >
```js
2019-03-06 05:18:18 +00:00
function idMatrix(n) {
2018-10-04 13:37:37 +00:00
return Array.apply(null, new Array(n)).map(function (x, i, xs) {
return xs.map(function (_, k) {
return i === k ? 1 : 0;
})
});
}
```
< / section >