xamples
epeat
ode
pproach
ptimize
est
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
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.
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
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
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]]
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
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
Instead, pass in a comparing function to arr.sort()