2.1 KiB
2.1 KiB
title | id | challengeType |
---|---|---|
Identity matrix | 5a23c84252665b21eecc7eb1 | 5 |
Description
1
s (ones), and all the other elements are all 0
s (zeroes).
- \(\displaystyle I_{n}=\begin{bmatrix} 1 & 0 & 0 \cr 0 & 1 & 0 \cr 0 & 0 & 1 \cr \end{bmatrix}\)
Instructions
n
as a parameter and returns the identity matrix of order \( n \times n \).
Tests
tests:
- text: <code>idMatrix</code> should be a function.
testString: assert(typeof idMatrix=='function');
- text: <code>idMatrix(1)</code> should return an array.
testString: assert(Array.isArray(idMatrix(1)));
- 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]);
Challenge Seed
function idMatrix(n) {
// Good luck!
}
After Test
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
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;
})
});
}