Skip to content

Commit 97b788e

Browse files
committed
Added hard/step_walking
1 parent 4822457 commit 97b788e

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

hard/step_walking.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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;

hard/step_walking.test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const stepWalking = require('./step_walking');
2+
3+
describe('stepWalking()', () => {
4+
test('passes Coderbyte.com tests', () => {
5+
expect(stepWalking(4)).toBe(5);
6+
7+
expect(stepWalking(5)).toBe(8);
8+
9+
expect(stepWalking(6)).toBe(13);
10+
11+
expect(stepWalking(7)).toBe(21);
12+
13+
expect(stepWalking(8)).toBe(34);
14+
15+
expect(stepWalking(9)).toBe(55);
16+
17+
expect(stepWalking(13)).toBe(377);
18+
});
19+
});

0 commit comments

Comments
 (0)