- 1

Can anyone help me with this Javascript project? I am unable to make the correct loop and so getting no output

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 var result = 5; while ( depth <= result ){ for(var i = 0;i++;){ result += 5; } console.log(i); } }

27th Oct 2021, 8:59 PM
Rubayet Kamal
Rubayet Kamal - avatar
6 ответов
+ 3
i recreate what Sanja Panic did in other way that could be more preferable let days = 0, result = 0, depth = 31; while (result <= depth) { result += 7; if (result < depth) result -= 2; console.log(`Day ${++days} : `, result); } https://code.sololearn.com/Wl9Gn0C9FkB0 Keep learning & happy coding :D
28th Oct 2021, 10:17 AM
SoloProg
SoloProg - avatar
+ 1
Sanja Panic Thanks a lot brother. I understood properly by going through your code.
27th Oct 2021, 10:10 PM
Rubayet Kamal
Rubayet Kamal - avatar
+ 1
SoloProg Thanks a lot Bruder
28th Oct 2021, 10:27 PM
Rubayet Kamal
Rubayet Kamal - avatar
0
Well your while loop is never activated because depth(31) is NOT less or equal to result (5). Also you miss logic inside for loop you set variable, you change its value but dont compare it. This is why loop dont give output
27th Oct 2021, 9:50 PM
PanicS
PanicS - avatar
0
Sanja Panic can you help me with the code? I am unable to figure out the inside part of the loop
27th Oct 2021, 9:55 PM
Rubayet Kamal
Rubayet Kamal - avatar
0
You need to check if current snail position (i named this result) is less than given depth. So while is less snail will go 7 feet, so add 7 to result, than check if it is still bigger than depth, so if it is, snail dont need to wait night(and go back 2 feet) so break loop. And else (if result is less than depth) remove that 2 feet from result. Also we need to count how many times we was inside loop(how many days) https://code.sololearn.com/W9SDWKlmT29a/?ref=app
27th Oct 2021, 10:04 PM
PanicS
PanicS - avatar