[英]Function that creates matrix 5x5 + function that creates HTML view of the matrix
我得到了以下任务:
“实现一个函数numberMatrix()
(使用 JS),它创建矩阵 5x5 的 HTML 视图,如下所述:
1 3 3 3 3
2 1 3 3 3
2 2 1 3 3
2 2 2 1 3
2 2 2 2 1
! 注意:不允许使用硬编码数组,例如
const arr = [[1,3,3,3,3], [2,1,3,3,3], [2,2,1,3,3], [2,2,2,1,3], [2,2,2,2,1]];
可以有其他一些数字。 尝试使用方阵术语和特征:主对角线、主对角线上/下的元素。
要生成 HTML 视图,请仅使用带有任何所需标签的document.write()
方法。
此外,建议实现单独的函数来生成矩阵(二维数组)和生成 HTML 视图。”
我知道如何创建硬编码矩阵的 HTML 视图:
function numberMatrix() {
let numbers = [
[1, 3, 3, 3, 3],
[2, 1, 3, 3, 3],
[2, 2, 1, 3, 3],
[2, 2, 2, 1, 3],
[2, 2, 2, 2, 1]
];
let x = 0;
while (x < 5) {
for (let i = 0; i < 5; i++) {
document.write(numbers[x][i]);
}
document.write('<br>');
x++;
}
}
我的主要问题是使用方阵项和特征来实现生成矩阵的函数:主对角线、主对角线上/下的元素,如上所述。
一些基本的想法:
对角线是外部数组和内部数组的索引相等的地方。
| 0 1 2 3 4 ---+--------------- 0 | 1 . . . . 1 | . 1 . . . 2 | . . 1 . . 3 | . . . 1 . 4 | . . . . 1
为了获得另一个对角线,您可以添加外部和内部数组的索引,并检查总和是否等于长度减一。
| 0 1 2 3 4 ---+--------------- 0 | . . . . 1 1 | . . . 1 . 2 | . . 1 . . 3 | . 1 . . . 4 | 1 . . . .
通过只取从 (0, 0) 到 (4, 4) 的第一个对角线,并通过再次查看索引,您会发现外部索引必须大于内部索引。
| 0 1 2 3 4 ---+--------------- 0 | . . . . . 1 | 2 . . . . 2 | 2 2 . . . 3 | 2 2 2 . . 4 | 2 2 2 2 .
var length = 5, matrix = Array.from( { length }, (_, i) => Array.from( { length }, (__, j) => i > j ? 2 : '.' // this is the check ) ); matrix.forEach(a => console.log(...a));
剩下的就是填满3
了,由你决定。
这是一个依赖于函数生成器的解决方案。
函数生成器buildSquaredMatrix
将负责生成方阵,提供它的大小、对角线所需的值、对角线下方元素所需的值以及对角线上方元素所需的值。
我不是数学大师,因此我很确定这可以通过不同的方式完成,但我只是希望这将帮助您发现其他方法来实现目标(例如,使用函数生成器)或为您提供更多信息关于您的问题的说明。
无论如何,此解决方案适用于任何大小的矩阵。
/** Builds a square matrix starting from the desired size. */ function *buildSquaredMatrix(size, diagonal, belowDiagonal, aboveDiagonal) { // Build each row from 0 to size. for (var i = 0; i < size; i++) { // Current array is composed by the "below diagonal" part, defined by the range 0 -> i, and the "above diagonal" part, defined by the range i -> size. // The concatenation will lead to an array of <size> elements. const current = Array.from({length: i}).fill(belowDiagonal).concat(Array.from({length: size - i}).fill(aboveDiagonal)); // finally, we set the diagonal item, which always is at index <i>. current[i] = diagonal; // then, we yield the current result to the iterator. yield current; } } // Below, we define a new 5x5 matrix /size 5), where the diagonal value is 1, the value below the diagonal is 2, and above is 3. for (var row of buildSquaredMatrix(5,1,2,3)) { // finally, we join the row with a blankspace, and separe the rows with a break. document.write(row.join(' ') + '<br />'); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.