0

# Help for The Snail in the Well (Javascript)

Can someone explain where did I do wrong? function main() { var depth = parseInt(readLine(), 10); //your code goes here var i = 0; //iteration var totalsteps = 0; //total steps taken //loop when totalsteps<depth while (totalsteps<depth){ j = i++; //iteration + 1 totalsteps = totalsteps + 7; //move up 7 steps at day if (totalsteps<depth){ totalsteps = totalsteps - 2; //if never reach depth by day, slide down 2 steps at night } } console.log(j) }

9 odpowiedzi

+ 1

i solve that question today. Use "while" and "if" condition. And look output "day" and "day-1" i dont want to say you answer. Because u need to try and every try make u strong. Good Luck

0

Hi! 1. j is superfluous, it can be removed.
2. add days at the end of the cycle.
3. what is the condition for the snail's exit from the pipe in the task? and what did you program?

0

Hi, I’m sorry. I do not understand. But this is the question.

0

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.

0

I know. And I try to you solve this task

0

did you write the code yourself? or did you get it somewhere?

0

I wrote it myself. I realized if i used j = i++, my days is always 1 day short. But i use i = i+1, i am able to get the correct days

0

For count days use i only. For count correct days use (<=) in "while" condition. Or use "for" loop

0

So I wasted a lot of time with the loop method, I decided to find a way to simplify the problem by exploring other options and this is what I came up with.
function main() {
var depth = parseInt(readLine(), 10);
day = depth/5;
console.log(Math.round(day));
}
We know that the snail moves 7 and slides back 2 each night; so that is 5 per day.
We know depth is determined by user input.
So we divide depth by 5 and we get a number and decimal.
Using the Math.round() function we eliminate our decimal and store the answer in the var day.
Hope this helps.