[英]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.