【发布时间】:2018-08-07 10:33:17
【问题描述】:
我正在处理来自 Codewars 的 this kata。任务是:
给定一个数,用它的位数可以得到多少个三的倍数?
假设你有数字 362。可以从中生成的数字是:
362 ----> 3, 6, 2, 36, 63, 62, 26, 32, 23, 236, 263, 326, 362, 623, 632
我编写了以下递归函数来计算所有可能性:
const findMult_3 = (num) => {
const powerset = (set) => {
const combinations = []
const combine = (prefix, chars) => {
for (let i = 0; i < chars.length; i++) {
const newPrefix = parseInt(prefix + chars[i])
if (!combinations.includes(newPrefix)) {
combinations.push(newPrefix)
} else {
console.log('encountered duplicate')
}
combine(newPrefix, chars.filter((x, ind) => ind !== i))
}
}
combine('', set)
return combinations.sort((a, b) => a - b)
}
const allCombinations = powerset(num.toString().split(''))
const factorsOfThree = allCombinations.filter(x => x % 3 === 0).filter(x => x !== 0)
return [factorsOfThree.length, factorsOfThree.pop()]
}
findMult_3(43522283000229)
我很早就注意到我遇到了很多重复案例,因此使用了console.log('encountered duplicate') 标志。
这个算法的执行对于大数字来说需要很长时间,例如43522283000229。
我怎样才能提高这段代码的性能,还是应该完全废弃它?
【问题讨论】:
标签: javascript algorithm performance combinations permutation