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

mwecs4sa  于 2022-12-21  发布在  Java
关注(0)|答案(2)|浏览(141)

假设我有一个数组keys = ["the?", "orange", "van", "s?"],在字符串的末尾有'?'表示它是可选的。
我想在javascript generateCombinations(keys)中使用一个函数,返回可能的组合,例如:
[["orange","van"],["the","orange","van"],["orange","van","s"],["the","orange","van","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;
}
iyfjxgzm

iyfjxgzm1#

您可以采用递归方法,只使用数组的第一项,如果数组为空则停止。

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(' ')));
wbgh16ku

wbgh16ku2#

下面是一个如何实现 *return数组的所有可能组合 * 的示例:

function getCombinations(arr, prefix = "") {
  let combinations = [];
  for (let i = 0; i < arr.length; i++) {
    let current = arr[i];
    let rest = arr.slice(i + 1);
    combinations.push(prefix + current);
    combinations = combinations.concat(getCombinations(rest, prefix + current));
  }
  return combinations;
}

let arr = ['a', 'b', 'c'];
let combinations = getCombinations(arr);
console.log(combinations);
// [  "a",  "ab",  "abc",  "ac",  "b",  "bc",  "c"]

相关问题