0

I keep getting an execution time out from my code for the challenge, Am I doing something wrong?

I am trying to do the Snail in the well JavaScript challenge and I have come up with the following code to try and solve it: Problem: The snail climbs up 7 feet each day and slips back 2 feet each night. How many days will it take the snail to get out of a well with the given depth? Sample Input: 31 Sample Output: 6 Explanation: Let's break down the distance the snail covers each day: Day 1: 7-2=5 Day 2: 5+7-2=10 Day 3: 10+7-2=15 Day 4: 15+7-2=20 Day 5: 20+7-2=25 Day 6: 25+7=32 So, on Day 6 the snail will reach 32 feet and get out of the well at day, without slipping back that night. My Code: function main() { var depth = parseInt(readLine(), 10); //your code goes here for (i = 0; depth > 0;i++){ day = (depth+2)-7; } console.log(day); } I keep getting execution timed out as an output which i am not expecting at all. Am I doing something wrong with my code? Or is it a problem on Sololearns end?

30th Dec 2020, 11:04 PM
Zach Best
Zach Best - avatar
5 Respostas
+ 6
function main() { var depth = parseInt(readLine(), 10); //your code goes here let climb = 0; let days = 0; while(true){ days++; climb += 7; if (climb >= depth){ break; } climb -= 2; } console.log(days); } Is the your problem?
31st Dec 2020, 1:05 AM
VṢtēphen
VṢtēphen - avatar
+ 2
Isn't that for loop infinite?
30th Dec 2020, 11:12 PM
Michal Doruch
+ 1
You don't change depth, but use it as condition in the loop. So the loop runs forever
30th Dec 2020, 11:17 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
0
function main() { var depth = parseInt(readLine(), 10); var a=depth; var b=0; for (x=5;true;x+=5) { if (x>a+2){ break; } b=b+1; }console.log(b); }
4th Jan 2021, 2:28 PM
Hbrian Khant
Hbrian Khant - avatar
- 1
Okay I have managed to solve the challenge using the following: function main() { var depth = parseInt(readLine(), 10); //your code goes here let day = Math.round(depth/5); console.log(day); } But it is isn't using a loop. I am a bit lost in how to apply a loop for this problem as my natural reaction was to use the code I have just written above. How could I write a loop to solve this challenge?
31st Dec 2020, 12:28 AM
Zach Best
Zach Best - avatar