freeCodeCamp/curriculum/challenges/japanese/10-coding-interview-prep/rosetta-code/identity-matrix.md

1.9 KiB

id title challengeType forumTopicId dashedName
5a23c84252665b21eecc7eb1 単位行列 5 302290 identity-matrix

--description--

単位行列 は、サイズ\( n \times n \) の正方行列であり、ここでは、対角線要素はすべて1、その他の要素はすべて0となります。

  • \(\displaystyle I_{n}=\begin{bmatrix} 1 & 0 & 0 \cr 0 & 1 & 0 \cr 0 & 0 & 1 \cr \end{bmatrix}\)

--instructions--

数値 n をパラメータとして取り、(n \times n \) 次の単位行列を返す関数を記述してください。

--hints--

idMatrix は関数とします。

assert(typeof idMatrix == 'function');

idMatrix(1) は配列を返す必要があります。

assert(Array.isArray(idMatrix(1)));

idMatrix(1)[ [ 1 ] ]を返す必要があります。

assert.deepEqual(idMatrix(1), results[0]);

idMatrix(2)[ [ 1, 0 ], [ 0, 1 ] ]を返す必要があります。

assert.deepEqual(idMatrix(2), results[1]);

idMatrix(3)[ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ]を返す必要があります。

assert.deepEqual(idMatrix(3), results[2]);

idMatrix(4)[ [ 1, 0, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 1 ] ]を返す必要があります。

assert.deepEqual(idMatrix(4), results[3]);

--seed--

--after-user-code--

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--

function idMatrix(n) {

}

--solutions--

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;
        })
    });
}