1

如果我们有以下数组:

["it", "wkppv", "ixoyx", "3452", "zzzzzzzzzzzz"]

如果我们试图获得k的所有可能的字符串组合 (在本例中为3),没有随机化,我们应该得到以下字符串:

'itwkppvixoyx'
'wkppvixoyx3452
'ixoyx3452zzzzzzzzzzzz'

因为当然,

"it" + "wkppv" + "ixoyx" = "itwkppvixoyx",

"wkppv" + "ixoyx" + "3452" = "wkppvixoyx3452",

"ixoyx" + "3452" + "zzzzzzzzzzzz" = "ixoyx3452zzzzzzzzzzzz"

但是我还没有找到创建这些字符串的方法。

我了解如何基于k创建包含第一个字符串和最后一个字符串的字符串,例如:

function createStrings (array, k) {
    let strings = [];
    for (let i = 0; i < array.length - (k - 1); i++) {
        strings.push(`${array[i]}${(array[i + (k-1)])}`);
    }    
    return strings;
}

console.log(createStrings(["it", "wkppv", "ixoyx", "3452", "zzzzzzzzzzzz"], 3));

但当然,这些都缺少“中间”元素。

如果k是 2 或 4 怎么办?我需要找到一种方法来创建包含数组中k连续字符串的字符串组合。关于如何做到这一点的任何想法?

4

2 回答 2

3

带有箭头功能地图的更短的替代方案:

const createStrings = (a, k) => a.slice(k - 1).map((v, i) => a.slice(i, i + k).join(''))

console.log( createStrings([1, 2, 3, 4, 5], 4) )
console.log( createStrings(["it", "wkppv", "ixoyx", "3452", "zzzzzzzzzzzz"], 3) )

于 2019-08-18T18:15:07.850 回答
3

这是滑动窗口的问题,其中窗口大小为k

解决方案是创建一个初始窗口,然后将其滑向末端。

我记录的解决方案在这里

function createCombinations(stringArray, k) {
    // Define an empty array to store combinations
    let result = [];

    // Make a combination for starting window
    let initialWindow = '';

    for (let i = 0; i < k; i++) {
        // '+' operator, by default string concatenation
        initialWindow += stringArray[i];
    }

    // Add it to Result array
    result.push(initialWindow);

    // Iterate over remaining stringArray element
    for (let i = k; i < stringArray.length; i++) {

        // For debugging
        // console.log('Initial Combination->', initialWindow, initialWindow.length);
        // console.log('Remove first entry->', stringArray[i-k], stringArray[i-k].length);
        // console.log('After remove->', initialWindow.slice(stringArray[i-k].length));

        // Remove k previous element and add next element
        initialWindow = initialWindow.slice(stringArray[i-k].length) + stringArray[i];

        // console.log('After add next->', initialWindow);

        result.push(initialWindow);
    }

    return result;
}

/* Tests */

console.log(createCombinations(['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight'], 3));
console.log(createCombinations(['This', 'is', 'Some', 'Random', 'String'], 4));
console.log(createCombinations(['What', 'Am', 'I', 'Doing', 'Here', 'Some', 'Other'], 2));
console.log(createCombinations(['1', '2', '3', '4', '5', '6', '7'], 3));

注意:如果您传递不带' '的数字,它将评估表达式而不是字符串连接。

于 2019-08-18T17:29:17.833 回答