我正在嘗試撰寫一個遞回函式,但我很掙扎,我希望有人能幫助我朝著正確的方向前進。我相信這將被視為“樹遞回”。
這是一個簡單的例子來說明資料和我正在嘗試做的事情。顯然,真實資料更復雜……
基本上,我從一個包含單個物件陣列的陣列開始,如下所示,其中任何物件中的 prop2 可以是有效字串或空字串...
[
[
{ prop1: "abc", prop2: "" },
{ prop1: "def", prop2: "one" },
{ prop1: "ghi", prop2: "" }
]
]
我的演算法需要查看上面的陣列并遍歷物件。一旦在 prop2 中遇到一個帶有空字串的物件,它就需要對陣列進行 3 次克隆,并像這樣用三個不同的值(一/二/三)替換該物件(并且僅該物件)中的空字串。 ..
[
[
{ prop1: "abc", prop2: "one" },
{ prop1: "def", prop2: "one" },
{ prop1: "ghi", prop2: "" }
],
[
{ prop1: "abc", prop2: "two" },
{ prop1: "def", prop2: "one" },
{ prop1: "ghi", prop2: "" }
],
[
{ prop1: "abc", prop2: "three" },
{ prop1: "def", prop2: "one" },
{ prop1: "ghi", prop2: "" }
]
]
Then the algorithm starts again, except that the the input is this new array containing three arrays.
So on the second iteration, each of the three arrays will get cloned three times and the empty string will get replaced in the same way.
The end result for this simple example would be an array of nine arrays.
If the array had more objects with empty prop2 values, there would be more iterations.
Basically, I'm taking an array of objects where some of the props are empty strings and "expanding" that particular prop value to every permutation of "one"/"two"/"three"
I know that this is an ideal problem for recursion but I'm having trouble figuring out the code.
我認為“基本情況”可能是我有一個物件陣列并且沒有一個物件具有空字串的屬性。這種情況將回傳該陣列。
除了用三個新創建的變體呼叫相同的函式三次之外,我不知道其他情況會是什么樣子。我也不知道這個案子應該回傳什么。
我在網上找不到與我正在嘗試做的類似的參考示例。
編輯:看看遞回回應,即使它們都有效,很明顯遞回解決方案并不像我想象的那么簡單。非遞回答案實際上是最好的答案。
uj5u.com熱心網友回復:
我建議使用這種非封閉式解決方案,它可以滿足您的最終結果要求:
const myTree = [
[
{ prop1: "abc", prop2: "" },
{ prop1: "def", prop2: "one" },
{ prop1: "ghi", prop2: "" }
]
];
let nodesWithEmptyStrings = myTree.filter(n=> !!n.find(l=> l.prop2===""));
while(nodesWithEmptyStrings.length > 0) {
nodesWithEmptyStrings.forEach(n => {
const firstEmptyStringLeaveIndex = n.findIndex(l=> l.prop2==="");
n[firstEmptyStringLeaveIndex].prop2 = "one";
const copy1 = JSON.parse(JSON.stringify(n));
copy1[firstEmptyStringLeaveIndex].prop2 = "two";
myTree.push(copy1);
const copy2 = JSON.parse(JSON.stringify(n));
copy2[firstEmptyStringLeaveIndex].prop2 = "three";
myTree.push(copy2);
});
nodesWithEmptyStrings = myTree.filter(n=> !!n.find(l=> l.prop2===""));
}
document.getElementById('result').innerText = JSON.stringify(myTree, null, 2);
<pre id="result"></pre>
uj5u.com熱心網友回復:
是的,您可以使用遞回來做到這一點。基本原理是先修改陣列,然后檢查是否需要再修改,如果是,則回傳新陣列呼叫函式的結果。
這是一個例子:
const fillers = ['one', 'two', 'three'];
const propToCheck = 'prop2';
function recursion(arr) {
const mod = arr.reduce((a, c) => {
const found = c.find(v => !v[propToCheck]);
if (found) {
const tmp = c.filter(v => v !== found);
return [...a, ...fillers.map(filler => [...tmp, { ...found, [propToCheck]: filler }])];
}
return [...a, c];
}, []);
const notDone = mod.some(v => v.some(o => !o[propToCheck]))
if (notDone) {
return recursion(mod);
}
return mod;
}
const result = recursion([
[
{ prop1: "abc", prop2: "" },
{ prop1: "def", prop2: "one" },
{ prop1: "ghi", prop2: "" }
]
]);
console.log(result);
uj5u.com熱心網友回復:
我不知道這是否是一個我想用遞回直觀地解決的問題,但是這個通用函式需要替換和檢查空字串作為引數的鍵將起作用(使用 es6 語法和功能很多解構):
const substitute = (data, index, keyToCheck, substitutes) => {
const indexOfObjectWithEmptyKeyToCheck = data[index].findIndex(obj => obj[keyToCheck] === "")
if(indexOfObjectWithEmptyKeyToCheck === -1) {
if(index === data.length - 1)
return data
else
return substitute(data, index 1, keyToCheck, substitutes)
}
else {
return substitute(
[
...data.slice(0, index),
...(substitutes.map(
substitute => [
...data[index].slice(0, indexOfObjectWithEmptyKeyToCheck),
{ ...data[index][indexOfObjectWithEmptyKeyToCheck], [keyToCheck]: substitute },
...data[index].slice(indexOfObjectWithEmptyKeyToCheck 1)
]
)),
...data.slice(index 1)
],
index,
keyToCheck,
substitutes
)
}
}
const SUBSTITUTES = ["one", "two", "three"];
const result = substitute(
[
[
{ prop1: "abc", prop2: "" },
{ prop1: "def", prop2: "one" },
{ prop1: "ghi", prop2: "" }
]
],
0,
"prop2",
SUBSTITUTES
)
console.log(result)
console.log("Size of result: " result.length)
基本上,我們遍歷陣列,只有在當前陣列沒有物件且要檢查的鍵是空字串的情況下才增加索引,否則我們會根據需要進行替換并在同一索引上遞回。基本情況是當要檢查的鍵不是空字串并且索引是輸入陣列的最后一個索引時。
我留給你的 Typescript 部分作為練習,因為我不認為輸入輸入資料是這里的大問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/439497.html
標籤:javascript 打字稿 递归
