1
I was looking for an answer to an exercise I’m doing and, the platform where I’m studying, returned with error what I wrote.
The exercise was:
Utopian trees grow in a particular way in two cycles:
- Each spring doubles its size
- Each summer grow a meter
If Laura plants a one meter utopian tree in late autumn, what would be her height after N cycles?
Some examples:
- si N = 0, your height will be 1 meter (nothing has grown)
- si N = 1, its height will be 2 meters (doubled the height in spring)
- si N = 2, its height will be 3 meters (grew one meter more in summer)
- si N = 3, its height will be 6 meters (doubled the height the next spring)
Write the function alturaArvoreUtopica, that uses an amount of growth cycles, and returns the resulting height of Laura’s tree.
My first solution was:
function alturaArvoreUtopica(ciclos){
var tamanhoDaArvore = 1;
for(var i = 1; i <= ciclos; i++){
if (i % 2 ===0) tamanhoDaArvore += 1;
} else {
tamanhoDaArvore *=2;
}
return tamanhoDaArvore
}
console.log(alturaArvoreUtopica);
However, when sending the exercise through the platform, it did not pass (I should have printed the error). I came in here to get something on and found here. exactly the same exercise, with the solution below (and that went through the platform):
function alturaArvoreUtopica(ciclos){
var tamanhoDaArvore = 1;
for (var i = 1; i <= ciclos; i++) {
if (i % 2 ===0) tamanhoDaArvore += 1;
else tamanhoDaArvore *= 2;
}
return tamanhoDaArvore;
}
console.log(alturaArvoreUtopica(4));
Doubt: I can not understand why what I wrote did not pass and, the second solution found here, passed. If anyone can help me with this understanding, it would help me a lot!
It is because you have a syntax error. The
else
is after thefor
(note the lock of keys before the wordelse
) and not ofif
– Jéf Bueno
Function alturaArvoreUtopica(cycles){var sizeDaArvore = 1;for (var i = 1; i <= cycles; i++) {if (i % 2 ===0){ sizeDaArvore += 1; }Else{ sizeDaArvore *= 2;}}Return sizeDaArvore;}console.log(highArvoretopica(4));;
– user60252
The code above runs giving 7 as reultado. It is in a line only pq here can only be so, but works well
– user60252
Great! Thank you, @Leocaracciolo!
– Cami Queiroz
And no problem @LINQ!
– Cami Queiroz