javascript - 在 JavaScript 中从 n 个对象和 r 个样本生成唯一的组合

标签 javascript node.js arrays

从带有 R 样本的 N 个对象中生成 JavaScript 中所有唯一组合的最佳方法是什么。例如:

n = [100,200,300,400]
r = 3

预期结果

    [100,200,300]
    [100,200,400]
    [200,300,400]
    [100,300,400]

我能够使用递归解决方案实现上述目标。但对于大型数据集(例如N=25,R=10)来说速度很慢。有没有更快的方法来实现这一目标?

最佳答案

好的,这里是维基百科中描述的顺序生成器的直接实现:

...track k index numbers of the elements selected, starting with {0 .. k−1} (zero-based) or {1 .. k} (one-based) as the first allowed k-combination and then repeatedly moving to the next allowed k-combination by incrementing the last index number if it is lower than n-1 (zero-based) or n (one-based) or the last index number x that is less than the index number following it minus one if such an index exists and resetting the index numbers after x to {x+1, x+2, …}. https://en.wikipedia.org/wiki/Combination#Enumerating_k-combinations

function combinations(a, c) {
    let index = []
    let n = a.length

    for (let j = 0; j < c; j++)
        index[j] = j
    index[c] = n

    let ok = true
    let result = []

    while (ok) {

        let comb = []
        for (let j = 0; j < c; j++)
            comb[j] = a[index[j]]
        result.push(comb)

        ok = false

        for (let j = c; j > 0; j--) {
            if (index[j - 1] < index[j] - 1) {
                index[j - 1]++
                for (let k = j; k < c; k++)
                    index[k] = index[k - 1] + 1
                ok = true
                break
            }
        }
    }

    return result
}

//

N = 25
R = 10
A = Array(N).fill(0).map((_, n) => n)

console.time()
combs = combinations(A, R)
console.log(combs.length, 'combinations')
console.timeEnd()

在我的机器上花费 < 1 秒。

关于javascript - 在 JavaScript 中从 n 个对象和 r 个样本生成唯一的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67720548/

相关文章:

c - 如何检查索引是否包含符号?

javascript - 在 node.js 中读取缓冲区对象

node.js - 从 Node.js 应用程序的 CSV 文件将多个条目导入 MongoDB

javascript - WordPress 插入新数据后刷新表

使用 OneLogin 实现 Node.js SAML

node.js - 使用 tsconfig-paths-webpack-plugin 会为 "Module not found"和其他标准模块提供 "fs"错误

javascript - 将php数组获取到js数组中

arrays - For Next 循环中每次迭代 VBS 中的新数组

javascript - 从 XYZ 解码并编码为 UTF8

javascript - 使用filter()函数删除嵌套数组中的元素