简体   繁体   English

查找所有可能的数字组合以获得给定的总和 - Python 到 Nodejs

[英]Finding all possible combinations of numbers to get a given sum - Python to Nodejs

Can anybody help me to convert this code to nodejs?有人可以帮我将此代码转换为 nodejs 吗?

def subset_sum(numbers, target, partial=[], partial_sum=0):

    if partial_sum == target:
        #print("partial_sum")
        #print(target)
        yield partial
    if partial_sum >= target:
        return

    #print(*enumerate(numbers))
    print(*partial)
    for i, n in enumerate(numbers):
        #print(i)
        remaining = numbers[i + 1:]

        yield from subset_sum(remaining, target, partial + [n], partial_sum + n)



list(subset_sum([1, 2, 3, 7, 7, 9, 10], 10))

If you implement your own enumerate function the translation to modern js is indeed almost 1:1.如果您实现自己的enumerate函数,那么对现代 js 的转换确实几乎是 1:1。

 console.log(Array.from(subsetSum([1, 2, 3, 7, 7, 9, 10], 10))) function* subsetSum(numbers, target, partial = [], partialSum = 0) { if (partialSum === target) yield partial if (partialSum >= target) return for(const [i, n] of enumerate(numbers)) { yield* subsetSum(numbers.slice(i + 1), target, [...partial, n], partialSum + n) } } function* enumerate(iterable) { let i = 0 for(const item of iterable) { yield [i++, item] } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 寻找数字的最佳子集组合以达到给定的总和或最接近它 - Finding the best possible subset combinations of numbers to reach a given sum or closest to it 寻找所有可能的组合 - Finding all possible combinations 使用API​​和Python查找字母的所有可能组合 - Finding All Possible Combinations of Letters using an API and Python 给定字符串的所有可能组合 - All possible combinations of a given string 获取所有可能的对象组合,其中值的总和与数字匹配 - Get All possible combinations of objects, where sum of values matches number 递归地获取Java中一组数字的所有可能组合 - Recursively get all possible combinations of a set of numbers in Javascript JavaScript Tic Tac Toe-查找数组中数字的所有可能组合 - JavaScript Tic Tac Toe - Finding All Possible Combinations of Numbers within an Array 如何在 JavaScript 中找到等于给定总和的三元组的所有可能组合? (“星星和酒吧”或“球和垃圾箱”问题) - How to find all possible combinations of triplets equaling a given sum in JavaScript? ('Stars and Bars' or 'Balls and Bins' problem) 返回数组中所有可能的数字组合,其总和小于或等于n - Return all possible combinations of numbers in an array whose sum is less than or equal to n 寻找最接近给定数字的数字总和 - Finding closest sum of numbers to a given number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM