0

Please can anyone explain to me why this code/logic does not work in Javascript??

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 I tried same logic in c++ and java and it worked fine with all inputs but in solo learn test cases it says my code does not work for input 42...the output becomes 1 instead of 8. function main() { var depth = parseInt(readLine(), 10); //your code goes here var distance,day=0; do{ day++; distance+=7; if(distance>depth){ break; }else{ distance-=2; } }while(distance<depth); console.log(day); }

17th Feb 2022, 11:00 PM
ARKOH-ADDO EBENEZER
ARKOH-ADDO  EBENEZER - avatar
3 Answers
+ 1
Here is some topic about declaring more variables in same line https://stackoverflow.com/questions/694102/declaring-multiple-variables-in-javascript Your syntax was wrong and make bug in code, but not error. distance is undefined, than you add number and it become NaN, thats why it dont show syntax error, but you run code only once because while condition is exualy false. for more variables in same line you need to add value to each of them and separete them with "," in java script, probably other languages have diferent syntax for this, and code work fine there but not here. var a = 0, b = 0;
17th Feb 2022, 11:14 PM
PanicS
PanicS - avatar
+ 2
You have problem because of variables var distance,day = 0; If you place tham in separate line var distance = 0; var day = 0; Your code will work except one case where you need to add if (distance >= depth) Not just ">" function main() { var depth = parseInt(readLine(), 10); //your code goes here var distance = 0; var day=0; do{ day++; distance+=7; if(distance>=depth){ break; }else{ distance-=2; } }while(distance<depth); console.log(day); }
17th Feb 2022, 11:12 PM
PanicS
PanicS - avatar
+ 1
@PanicS thanks so much for the explanation and the resource you shared was very helpful.... but with the suggestion of if(distance>=depth) does not exactly satisfy the solution requirement... At the point when the distance == depth the snail cannot be considered to be out of the well. It must cross the depth to be considered out of it. thats why I used > instead of >=. thanks so much.
18th Feb 2022, 10:49 AM
ARKOH-ADDO EBENEZER
ARKOH-ADDO  EBENEZER - avatar