Can anybody help me to convert this code to 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.
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] } }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.