Как сгенерировать все комбинации с заменой переменной массива? - PullRequest
0 голосов
/ 10 ноября 2019

Я пытаюсь сгенерировать все возможные комбинации массива с undefined в качестве значения замены.

Значения массива зафиксированы на месте.

Так, например, мыиметь этот массив (массив может иметь длину x):

const items = [1, 2];

Функция, которую я пытаюсь построить, должна сгенерировать:

[
 [1, 2],
 [1, undefined],
 [undefined, 2],
 [undefined, undefined]
]

1 Ответ

1 голос
/ 10 ноября 2019

Вот, пожалуйста. Я надеюсь, что дополнительные комментарии заменят длинный и скучный пролог.

/* your array to work with. the length does not matter as the algorithm adapts to it */
const items = [1, 2, 3, 4];

/* the array containing the results */
const resultSet = [];

/* the number of rounds you need to create all possible combinations */
const maxRounds = Math.pow(2, items.length);

/* first we add the original list to the result set */
resultSet.push(items);

/* now we do the number of rounds, starting with index 1, until all combinations are set */
for (let round = 1; round < maxRounds; round++)
{
    /* create a clone, in order to not manipulate the original array by reference */
    const result = JSON.parse(JSON.stringify(items));

    /* generate the binary representation of the current round */
    /* this gives us a combination of only zeros ans ones */
    let binary = Number(round).toString(2);

    /* if the length doesn't match, add one additional zero to the left side */
    if (binary.length < items.length)
    {
        binary = '0' + binary;
    }

    /* now walk the line of 0s and 1s and decide whether to set 'undefined' or not */
    for (let pointer = 0; pointer < items.length; pointer++)
    {
        if (binary[pointer] === '1')
        {
            result[pointer] = undefined;
        }
    }

    /* add the new array to the result set */
    resultSet.push(result);
}

/* see the final list */
console.log(resultSet);
...