recursion
hackerrank.com/challenges/the-power-sum/problem
1 2 3 4 5 6 7 8 9 10
| function powerSum(x, n, i=1) { const num = Math.pow(i, n); if(num<x) { return powerSum(x, n, i+1) + powerSum(x-num, n, i+1); } else if(num === x) { return 1; } else { return 0; } }
|
https://www.hackerrank.com/challenges/recursive-digit-sum/problem
1 2 3 4 5 6
| function superDigit(n, k=1) { if(n<10) { return n; } return superDigit(k*String(n).split('').reduce((acc, val) => acc+Number.parseInt(val), 0), 1); }
|
combinations
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| const coins=[1,5,10,50]; function combination(num,coins) { const result = []; function combinehelper(num, indexofcoins, temp=[]) { let combine=[...temp]; if(indexofcoins<coins.length ){ if( num<0){ combine.pop() } else if(num===0){ result.push(combine); } else if(num>0){ combine.push(coins[indexofcoins]); combinehelper(num-coins[indexofcoins],indexofcoins, combine); combinehelper(num,indexofcoins+1, temp); } } } combinehelper(num, 0, temp); return result; } console.log(combination(11,coins))
|
https://algodaily.com/challenges/the-coin-change-problem
https://gist.github.com/jeanlauliac/8674996
https://www.codewars.com/kata/54d81488b981293527000c8f/javascript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const sumPairs = (ints, s) => { if (ints.length < 2) { return undefined; } let set = new Set(); set.add(ints[0]); for (let i=1; i < ints.length; i++) { let checkedNum = s-ints[i]; if (set.has(checkedNum)) { return [checkedNum,ints[i]]; } set.add(ints[i]); } return undefined; }
|