|
| 1 | +/** |
| 2 | + * Using the JavaScript language, have the function stepWalking(num) take the |
| 3 | + * num parameter being passed which will be an integer between 1 and 15 that |
| 4 | + * represents the number of stairs you will have to climb. You can climb the set |
| 5 | + * of stairs by taking either 1 step or 2 steps, and you can combine these in |
| 6 | + * any order. So for example, to climb 3 steps you can either do: (1 step, 1 |
| 7 | + * step, 1 step) or (2, 1) or (1, 2). So for 3 steps we have 3 different ways to |
| 8 | + * climb them, so your program should return 3. Your program should return the |
| 9 | + * number of combinations of climbing num steps. |
| 10 | + * |
| 11 | + * https://www.coderbyte.com/results/bhanson:Step%20Walking:JavaScript |
| 12 | + * |
| 13 | + * @param {number} num |
| 14 | + * @return {number} |
| 15 | + */ |
| 16 | +function stepWalking(num) { |
| 17 | + if (!Number.isInteger(num) || num < 0) { |
| 18 | + return -1; |
| 19 | + } |
| 20 | + |
| 21 | + // Define step increments. Can be anything. |
| 22 | + const stepIncrements = [1, 2]; |
| 23 | + |
| 24 | + // Will store all resulting valid combination of steps |
| 25 | + const stepCombos = []; |
| 26 | + |
| 27 | + // Iterative breadth-first search |
| 28 | + let queue = stepIncrements.map(num => [num]); |
| 29 | + while (queue.length !== 0) { |
| 30 | + const nextQueue = []; |
| 31 | + |
| 32 | + queue.forEach(stepList => { |
| 33 | + const sum = stepList.reduce((sum, value) => (sum += value), 0); |
| 34 | + |
| 35 | + if (sum === num) { |
| 36 | + stepCombos.push(stepList); |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + stepIncrements.forEach(increment => { |
| 41 | + if (sum + increment <= num) { |
| 42 | + const stepListCopy = stepList.slice(); |
| 43 | + stepListCopy.push(increment); |
| 44 | + nextQueue.push(stepListCopy); |
| 45 | + } |
| 46 | + }); |
| 47 | + }); |
| 48 | + |
| 49 | + queue = nextQueue; |
| 50 | + } |
| 51 | + |
| 52 | + return stepCombos.length; |
| 53 | +} |
| 54 | + |
| 55 | +module.exports = stepWalking; |
0 commit comments