Advertisement
Spocoman

04. Walking

Dec 28th, 2021 (edited)
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function walking(input) {
  2.     let stepSum = 0;
  3.     for (let i = 0; i < input.length; i++){
  4.         if (input[i] !== "Going home"){
  5.             stepSum += Number(input[i]);
  6.         }
  7.     }
  8.     if (stepSum < 10000) {
  9.         console.log(`${10000 - stepSum} more steps to reach goal.`);
  10.     } else {
  11.         console.log(`Goal reached! Good job!\n${stepSum - 10000} steps over the goal!`);
  12.     }
  13. }
  14.  
  15. Решение с тернарен оператор:
  16.  
  17. function walking(input) {
  18.     let stepSum = 10000;
  19.     for (let i = 0; i < input.length; i++) {
  20.         stepSum -= input[i] !== "Going home" ? Number(input[i]) : 0;
  21.     }
  22.     console.log(stepSum > 0 ? `${stepSum} more steps to reach goal.` :
  23.         `Goal reached! Good job!\n${Math.abs(stepSum)} steps over the goal!`);
  24. }
  25.  
  26. Или с while():
  27.  
  28. function walking(input) {
  29.     stepSum = 10000;
  30.     while (stepSum > 0) {
  31.         if (input[0] === "Going home"){
  32.             stepSum -= Number(input[1]);
  33.             break;
  34.         }
  35.         stepSum -= Number(input.shift());
  36.     }
  37.     console.log(stepSum > 0 ? `${stepSum} more steps to reach goal.`
  38.     : `Goal reached! Good job!\n${Math.abs(stepSum)} steps over the goal!`);
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement