Advertisement
Spocoman

Walking

Oct 13th, 2023
780
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!`);
  12.     }
  13.     return;
  14. }
  15.  
  16. Решение с тернарен оператор:
  17.  
  18. function walking(input) {
  19.     let stepSum = 10000;
  20.     for (let i = 0; i < input.length; i++) {
  21.         stepSum -= input[i] !== "Going home" ? Number(input[i]) : 0;
  22.     }
  23.     console.log(stepSum > 0 ? `${stepSum} more steps to reach goal.` :
  24.         `Goal reached! Good job!`);
  25.     return;
  26. }
  27.  
  28. Или с while():
  29.  
  30. function walking(input) {
  31.     stepSum = 10000;
  32.     while (stepSum > 0) {
  33.         if (input[0] === "Going home"){
  34.             stepSum -= Number(input[1]);
  35.             break;
  36.         }
  37.         stepSum -= Number(input.shift());
  38.     }
  39.     console.log(stepSum > 0 ? `${stepSum} more steps to reach goal.`
  40.     : `Goal reached! Good job!`);
  41.     return;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement