finalHP
with Carmen Salas • 2024/11/13
Solution
/*
**Problem**
Given an initialHP: Number and deltas: Array:
We simulate a 'game' where each index of the array is a 'level' which
mutates initialHP. We are supposed to return the 'end' state of initialHP
after it goes through all the mutations specified by the 'deltas' array.
**Examples/Edge Cases:**
initialHP: 0
deltas: [-12, 24, -36, 1, -2, 3]
output: 3
**Data Structures**
- Arrays
- Number
**Algorithm**
Iterate through the 'deltas' array:
- for each item, mutate iniitialHP based on its value
- if initialHP is to go under 0, set its value back to 0.
- if initialHP is to go over 100, set its value back to 100.
Return the final hp.
*/
function solution(initialHP, deltas) {
// hom and reduce
return deltas.reduce((hp, delta) => {
const temp = hp + delta;
if (temp < 0) return 0;
else if (temp > 100) return 100;
else return temp;
}, initialHP)
// for loop
for (let i = 0; i < deltas.length; i++) {
const temp = initialHP + deltas[i];
if (temp < 0) initialHP = 0;
else if (temp > 100) initialHP = 100;
else initialHP = temp;
}
return initialHP;
}
Last updated