gpt4 book ai didi

javascript - 返回数组与可选字符串的所有可能组合

转载 作者:行者123 更新时间:2023-12-05 05:29:44 25 4
gpt4 key购买 nike

假设我有一个数组 keys = ["the?", "orange", "van", "s?"],带有 '?'在字符串的末尾表示它是可选的。

我想要 javascript generateCombinations(keys) 中的一个函数,它返回可能的组合,例如:

[["orange","van"],["the","orange","van"],["orange","van","s"],["the", “橙色”,“货车”,“s”]]

删除“?”的一种可能方法就是简单地做一个 replace("?',"")

我觉得它可能需要一个递归函数,我还不是很擅长。感谢帮助!

到目前为止我已经试过了:

function isOptionalKey(key) {
return key.endsWith('?');
}

function hasOptionalKey(keys) {
return keys.some(isOptionalKey);
}

function stripOptionalSyntax(key) {
return key.endsWith('?') ? key.slice(0, -1) : key;
}


function generateCombinations(keys) {
if (keys.length === 1) {
return keys;
}

const combinations = [];

const startKey = keys[0];
const restKeys = keys.slice(1);

if (hasOptionalKey(restKeys)) {
const restCombinations = isOptionalKey(startKey)
? generateCombinations(restKeys)
: restKeys;

if (isOptionalKey(startKey)) {
combinations.push(restCombinations);
}
combinations.push(
restCombinations.map((c) => [stripOptionalSyntax(startKey), ...c])
);
} else {
if (isOptionalKey(startKey)) {
combinations.push(restKeys);
}
combinations.push([stripOptionalSyntax(startKey), ...restKeys]);
}

return combinations;
}

最佳答案

您可以通过仅使用数组的第一项并在数组为空时停止来采用递归方法。

const
getCombinations = array => {
if (!array.length) return [[]];
const
sub = getCombinations(array.slice(1)),
optional = array[0].endsWith('?'),
raw = optional ? array[0].slice(0, -1) : array[0],
temp = sub.map(a => [raw, ...a]);

return optional
? [...temp, ...sub]
: temp;
};
keys = ["the?", "orange", "van", "s?"],
result = getCombinations(keys);

console.log(result.map(a => a.join(' ')));

关于javascript - 返回数组与可选字符串的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74863704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com