--- title: Identity matrix id: 5a23c84252665b21eecc7eb1 challengeType: 5 forumTopicId: 302290 localeTitle: Единичная матрица --- ## Description
Единичная матрица является квадратной матрицей размера \ (n \ times n \), где диагональные элементы - все 1 s (одни), а все остальные элементы - все 0 s (нули). \ begin {bmatrix} 1 & 0 & 0 \ cr 0 & 1 & 0 \ cr 0 & 0 & 1 \ cr \ end {bmatrix} Напишите функцию, которая принимает число «n» в качестве параметра и возвращает единичную матрицу порядок nx n.
## Instructions
Write a function that takes a number n as a parameter and returns the identity matrix of order \( n \times n \).
## Tests
```yml tests: - text: idMatrix should be a function. testString: assert(typeof idMatrix=='function'); - text: idMatrix(1) should return an array. testString: assert(Array.isArray(idMatrix(1))); - text: idMatrix(1) should return [ [ 1 ] ]. testString: assert.deepEqual(idMatrix(1),results[0]); - text: idMatrix(2) should return [ [ 1, 0 ], [ 0, 1 ] ]. testString: assert.deepEqual(idMatrix(2),results[1]); - text: idMatrix(3) should return [ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ]. testString: assert.deepEqual(idMatrix(3),results[2]); - text: idMatrix(4) should return [ [ 1, 0, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ] ]. testString: assert.deepEqual(idMatrix(4),results[3]); ```
## Challenge Seed
```js function idMatrix(n) { // Good luck! } ```
### After Tests
```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 ] ]] ```
## Solution
```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; }) }); } ```