I need help with Snail in The Well project | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I need help with Snail in The Well project

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. I need help with this. I don't understand why I get just test case 2, 4 and 5. Can someone help me? If you help, thanks. My code: function main() {     var depth = parseInt(readLine(), 10);     //your code goes here     x = 0     for(y = 0; x <= depth;x = x){         x += 7;         if(x == depth){             break         }         x -= 2         if(x == depth){             break;         }         y++     }     console.log(y) }

1st Jan 2021, 5:21 PM
Siili00
7 Answers
+ 6
function main() { var depth = parseInt(readLine(), 10); //your code goes here var day = 0; var total = 0; while (total < depth) { day = day + 1; total = total + 7; if (total >= depth) { console.log(day); break; } total = total - 2; } }
2nd Jan 2021, 3:25 AM
K.S.S. Karunarathne
K.S.S. Karunarathne - avatar
+ 2
Thanks
1st Jan 2021, 6:34 PM
Siili00
+ 2
If it's not too much to ask, could someone explain this code to me? Like what happened there? I'd appreciate it
5th Jan 2021, 2:46 PM
fernie
fernie - avatar
+ 1
I recommend first link in first answer. There first create two variables called A and day. Then create a while loop what repeats until A is higher than or same as depth. There you increase A by 7(A is the position where snail is). Then you increase day by 1, break if A is higher than or same as depth. Then you just decrease A by 2 and print day to log outside the loop. I hope that this explanation is enough and you understand it.
5th Jan 2021, 4:20 PM
Siili00
0
crystal clear. very much appreciated. thanks :)
5th Jan 2021, 4:50 PM
fernie
fernie - avatar
0
I tried this one. It turned out correct but I’m not sure if it’s the proper one for(x=1; x < depth; x++){ let y = x+(x*4); if ((y+2)>=depth){ break; } } console.log(x)
27th Apr 2022, 7:45 AM
Ky Le
Ky Le - avatar