我不確定以遞回方式進行此操作的正確方法。假設我有兩個陣列
array1 = [a, null, c, d, e]
array2 = [1, 2, 3]
我想創建表單的結果陣列
[
[a, 1, c, d, e],
[a, 2, c, d, e],
[a, 3, c, d, e]
]
其中第二個陣列的每個元素都填充了 null 的位置。我可以很好地做到這一點,但是如果我有兩個 null 情況怎么辦?
array1 = [a, null, c, null, e]
array2 = [1, 2, 3]
我如何獲得以下內容?
[
[a, 1, c, 1, e],
[a, 1, c, 2, e],
[a, 1, c, 3, e],
[a, 2, c, 1, e],
...
[a, 3, c, 3, e]
]
uj5u.com熱心網友回復:
Javascript代碼:
let array1 = ['a', null, 'c', null, 'e']
let array2 = [1, 2, 3]
let output = []
let cursorPosition = 0; // cursorPosition is a pointer for `array2` index
let nullPositions = []
// find nullable positions; in our case here will be 1, 4
for (let i = 0; i < array1.length; i ) {
if (array1[i] === null) {
nullPositions.push(i)
}
}
// find total expected numbers of arrays from given input and create that array
const totalArray = Math.pow(array2.length, nullPositions.length);
for (let i = 0; i < totalArray; i ) {
output.push([...array1])
}
// replacement logic for the `null` values
for (let i = 0; i < nullPositions.length; i ) {
cursorPosition = 0;
// frequency: how often the cursor needs to change (depends on null position)
let frequency = totalArray / Math.pow(array2.length, i 1);
let resetCursorPositionOn = frequency;
for (let j = 0; j < output.length; j ) {
if (j < resetCursorPositionOn) {
output[j][nullPositions[i]] = array2[cursorPosition];
} else {
resetCursorPositionOn = frequency;
cursorPosition ;
if (cursorPosition === array2.length) {
cursorPosition = 0;
}
output[j][nullPositions[i]] = array2[cursorPosition];
}
}
}
console.log(output);
輸出:
[
["a",1,"c",1,"e"],
["a",1,"c",2,"e"],
["a",1,"c",3,"e"],
["a",2,"c",1,"e"],
["a",2,"c",2,"e"],
["a",2,"c",3,"e"],
["a",3,"c",1,"e"],
["a",3,"c",2,"e"],
["a",3,"c",3,"e"]
]
它適用于任意數量的組合。
uj5u.com熱心網友回復:
您描述的第一種情況是map模式的實體,第二種情況是 -- flatMap。
換個角度看,map就像一個回圈,flatMap又像一個兩級嵌套回圈,從最深的一級回圈開始,一個一個地創建結果的元素:
地圖:
for x in [1, 2, 3]:
let res = { result of replacing
the first `null` with `x`
in [a, null, c, d, e] }
yield res
-------------------------
[a, null, c, d, e]
----------------------
1 [a, 1, c, d, e],
2 [a, 2, c, d, e],
3 [a, 3, c, d, e]
平面圖:
for x in [1, 2, 3]:
let res = { result of replacing
the first `null` with `x`
in [a, null, c, null, e] }
for x in [1, 2, 3]:
let res2 = { result of replacing
the first `null` with `x`
in res } ## res NB!
yield res2
-------------------------
[ a, null, c, null, e ]
-------------------------
1: [ a, 1, c, null, e ],
1 [a, 1, c, 1 , e],
2 [a, 1, c, 2 , e],
3 [a, 1, c, 3 , e],
2: [ a, 2, c, null, e ],
1 [a, 2, c, 1 , e],
2 [a, 2, c, 2 , e],
3 [a, 2, c, 3 , e],
3: [ a, 3, c, null, e ]
1 [a, 3, c, 1 , e],
2 [a, 3, c, 2 , e],
3 [a, 3, c, 3 , e]
第一個就像用[1,2,3]替換結果替換每個元素;第二個就像用替換結果串列替換每個元素并將結果[1,2,3]串列附加在一起; 即將結果串列的元素拼接到位;即創建組合地圖,展平(因此得名,)。flatMap
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/425225.html
上一篇:遞回查找鏈中的元素
下一篇:不保留內容的串列串列
