+ 3

Can anyone give the solution of the snail challenge?

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.

8th Feb 2021, 5:57 PM
Imtiaz Faisal
Imtiaz Faisal - avatar
9 Respuestas
+ 2
sorry but the challenges are for you to learn. just giving you the answer most likely wont help you. so please show your attemps
8th Feb 2021, 6:19 PM
Brain & Bones
Brain & Bones - avatar
+ 2
Imtiaz Faisal i suggest using the while loop. if you show me what you tried i can tell you where you went wrong.
8th Feb 2021, 6:53 PM
Brain & Bones
Brain & Bones - avatar
+ 2
glad you could follow along. 😁 happy coding 😉
8th Feb 2021, 7:14 PM
Brain & Bones
Brain & Bones - avatar
+ 1
I have tried several times with for loop but couldn't get it. Just give me the logic. Thank you!
8th Feb 2021, 6:29 PM
Imtiaz Faisal
Imtiaz Faisal - avatar
+ 1
function main() { var depth = parseInt(readLine(), 10); //your code goes here var days = 0; var d = 0; while (true) { d += 7; d++; console.log(d); if(d>=depth) { break; console.log (d); d -= 2 } console.log(days); } }
8th Feb 2021, 6:56 PM
Imtiaz Faisal
Imtiaz Faisal - avatar
+ 1
ok so there are a couple problems. first. first, remove any console.log(d); they are not needed. next, to make sure you only print the days onces, move the console.log(days); outside the while loop. right before the end of the function.....
8th Feb 2021, 7:05 PM
Brain & Bones
Brain & Bones - avatar
+ 1
then you need to change d++; to days++;....
8th Feb 2021, 7:06 PM
Brain & Bones
Brain & Bones - avatar
+ 1
finally your if function is wrong; you need to move d-=2; into an else function
8th Feb 2021, 7:08 PM
Brain & Bones
Brain & Bones - avatar
+ 1
Thanks a lot Sir! The code is now working 😊
8th Feb 2021, 7:12 PM
Imtiaz Faisal
Imtiaz Faisal - avatar