R
E
A
C
T
O
xamples
epeat
ode
pproach
ptimize
est
{Stone Trails}
The Stone Trails
While Cindy is out on a hike with friends, she finds a trail of stones with numbers on them. She starts following the trail and notices that consecutive stones have a difference of either A or B. Legend has it that there is a treasure trove at the end of the trail, and if Cindy can guess the value of the last stone, the treasure will be hers.
0
1
3
5
?
6
The Challenge
Write a function that takes an array of stone trails and returns an array of the possible values (in ascending order) of the last stone for each trail, with the results for each trail in a nested array.
An array of...wait - what's a stone trail?
A stone trail is represented by an array [x, a, b] where:
- x is the number of stones in the trail
- a is value A
- b is value B
IMPORTANT NOTES:
- The value of the first stone is always 0
- The numbers on the stones are in increasing order
Simple Example
EXAMPLE: Given [[3, 1, 2]], return 2 3 4.
0
1
2
0
1
3
0
2
4
0
2
3
1
1
1
2
2
2
2
1
Tests to Run
Input: [[3, 1, 2]]
Output: [[2, 3, 4]]
Input: [[3, 1, 2], [4, 10, 100]]
Output: [[2, 3, 4], [30, 120, 210, 300]]
Input: [[5, 3, 23], [73, 25, 25], [12, 73, 82]]
Output: [[12, 32, 52, 72, 92], [1800], [803, 812, 821,
830, 839, 848, 857, 866, 875, 884, 893, 902]]
The Approach
- Run through each combination of A and B that will produce a unique result
- AAAAAA
- AAAAAB
- AAAABB
- AAABBB
- AABBBB
- ABBBBB
- BBBBBB
function stoneNumsStack(arr) {
return arr.reduce(function(answer, innerArr) {
answer.push(lastStoneVals.apply(null, innerArr));
return answer;
}, []);
}
function lastStoneVals(numStones, valA, valB) {
var sum = 0,
counter = 0,
results = [];
if (valA === valB) {
sum = valA * (numStones - 1);
results.push(sum);
} else {
while (counter < numStones) {
var a = (valA < valB) ? valA : valB;
var b = (valA < valB) ? valB : valA;
sum += a * (numStones - counter -1);
sum += b * counter;
results.push(sum);
sum = 0;
counter++;
}
}
return results;
}
function stoneNumsStack(arr) {
return arr.reduce(function(answer, innerArr) {
answer.push(lastStoneVals.apply(null, innerArr));
return answer;
}, []);
}
function stoneNumsStack(arr) {
var answer = [];
arr.forEach(function(innerArr) {
var results = lastStoneVals(innerArr[0], innerArr[1], innerArr[2]);
answer.push(results);
});
return answer;
}
same result as
Using reduce and apply
var arr = [100, 20, 15, 8];
console.log(arr.sort());
--> [100, 15, 20, 8]
var arr = [100, 20, 15, 8];
function sortingFunc(a, b) {
return a - b;
}
console.log(arr.sort(sortingFunc));
--> [8, 15, 20, 100];
You cannot just do arr.sort() for numbers
If your partner sorts an array of numbers..
Instead, pass in a comparing function to arr.sort()
Concepts Covered
- Combinations (AAA, AAB, ABB, etc..), but not permutations (AAB, ABA, BAA)
- Refactoring
- Separate out into multiple functions?
- Use prototypal methods (like reduce and apply)?
Reacto: Stone Trails
By Katie Peters
Reacto: Stone Trails
- 1,361