祝大家有美好的一天!
遇到了問題。我對數學不是很好,但是,程式有必要根據以下示例從矩陣 (w) 中選擇 2 個子矩陣 (subMatrixA, subMatrixB):
// main matrix
final w = [
[0, 0.6, 0.3, 0.3, 0.5, 0.5],
[0.9, 0, 0.7, 0.8, 0.2, 0.5],
[0.2, 0.8, 0, 0.4, 0.6, 0.3],
[0.1, 0.7, 0.6, 0, 0.7, 0.2],
[0.9, 0.8, 0.5, 0.3, 0, 0.7],
[0.8, 0.6, 0.3, 0.7, 0.7, 0],
];
// a - array of indexes in w matrix (rows and columns)
function selection(a) {...} // need an algorithm
// call function with algorithm
selection([0, 1]) // which means - 0 and 1 line
// result
subMatrixA =
[
[0, 0.6]
[0.9, 0 ]
]
subMatrixB =
[
[0.3, 0.3, 0.5, 0.5]
[0.7, 0.8, 0.2, 0.5]
]
我該怎么做?希望能得到你的幫助,謝謝。
我試圖撰寫演算法代碼,但我在演算法和數學方面非常糟糕......
uj5u.com熱心網友回復:
操場
(你可能需要在: number[]這里洗掉型別,我用打字稿寫)
// main matrix
const w = [
[0, 0.6, 0.3, 0.3, 0.5, 0.5],
[0.9, 0, 0.7, 0.8, 0.2, 0.5],
[0.2, 0.8, 0, 0.4, 0.6, 0.3],
[0.1, 0.7, 0.6, 0, 0.7, 0.2],
[0.9, 0.8, 0.5, 0.3, 0, 0.7],
[0.8, 0.6, 0.3, 0.7, 0.7, 0],
];
function selection(
source: number[][],
rowIndexes: number[],
columnIndexes: number[] = rowIndexes,
): number[][] {
return rowIndexes.map(
y => columnIndexes.map(
x => source[y][x]
)
);
}
let A = selection(w, [0, 1])
// ^?
console.log(A)
// ^ [[0, 0.6], [0.9, 0]]
function otherIndexes(
indexes: number[],
length: number,
): number[] {
// make [0, 1, 2, ..., length-1] and filter it
return Array.from({ length }, (e, i) => i)
.filter(i => !indexes.includes(i));
}
let B = selection(w, [0, 1], otherIndexes([0, 1], w[0].length))
console.log(B)
// ^ [[0.3, 0.3, 0.5, 0.5], [0.7, 0.8, 0.2, 0.5]]
uj5u.com熱心網友回復:
如果我正確理解您的要求,那么只需取出他需要的行,然后根據我們正在尋找的行數對每個結果行進行切片。
const selection = (matrix, rows, count = rows .length) => [
rows .map (r => matrix [r]) .map (r => r .slice (0, count)),
rows .map (r => matrix [r]) .map (r => r .slice (count)),
]
const w = [[0, 0.6, 0.3, 0.3, 0.5, 0.5], [0.9, 0, 0.7, 0.8, 0.2, 0.5], [0.2, 0.8, 0, 0.4, 0.6, 0.3], [0.1, 0.7, 0.6, 0, 0.7, 0.2], [0.9, 0.8, 0.5, 0.3, 0, 0.7], [0.8, 0.6, 0.3, 0.7, 0.7, 0]]
const [matrixA, matrixB] = selection (w, [0, 1])
console .log ('matrixA: ', matrixA)
console .log ('matrixB: ', matrixB)
.as-console-wrapper {max-height: 100% !important; top: 0}
這可以通過row .map (...)只呼叫一次來稍微提高效率。這不是一個困難的改變,但它會使代碼更難看。
沒有錯誤檢查;如果您提供超出范圍的行,任何事情都可能發生。同樣,這并不難解決,但我把它留給讀者作為練習。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/530400.html
上一篇:FlutterTest在測驗中拋出“PlatformException(通道錯誤,無法在通道上建立連接。,null,null)”但在應用程式中沒有
