Liliana797979

Ladybugs - fundamentals

Jun 12th, 2021
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.      
  2. function ladybugs(arr) {
  3.   let sizeOfField = arr[0];
  4.   let initialIndexes = arr[1];
  5.   initialIndexes = initialIndexes.split(" ");
  6.   let commands = arr.slice(2);
  7.   let field = [];
  8.  
  9.   for (let i = 0; i < sizeOfField; i++) {
  10.     field.push(0);
  11.   }
  12.  
  13.   for (let i = 0; i < initialIndexes.length; i++) {
  14.     let position = Number(initialIndexes[i]);
  15.     if (position > field.length - 1) {
  16.       continue;
  17.     }
  18.     field[position] = 1;
  19.   }
  20.  
  21.  
  22.   for (let i = 0; i < commands.length; i++) {
  23.     let currentCommand = commands[i];
  24.     currentCommand = currentCommand.split(" ");
  25.  
  26.     let position = Number(currentCommand[0]);
  27.     let direction = currentCommand[1];
  28.     let flyCount = Number(currentCommand[2]);
  29.  
  30.     if (field[position] === 0
  31.       || position < 0
  32.       || position > field.length - 1) {
  33.       continue;
  34.     }
  35.  
  36.     field[position] = 0;
  37.    
  38.     if (flyCount < 0) {
  39.       direction = direction === "right" ? "left" : "right";
  40.       flyCount = Math.abs(flyCount);
  41.     }
  42.    
  43.     let nextPosition = 0;
  44.  
  45.     if (direction === "right") {
  46.       nextPosition = position + flyCount;
  47.     } else if (direction === "left") {
  48.       nextPosition = position - flyCount;
  49.     }
  50.  
  51.     while (field[nextPosition] === 1) {      
  52.       if (direction === "right") {
  53.         nextPosition += flyCount;
  54.       } else if (direction === "left") {
  55.         nextPosition -= flyCount;
  56.       }
  57.     }
  58.    
  59.     if (nextPosition > field.length - 1 || nextPosition < 0) {
  60.       continue;
  61.     }
  62.  
  63.     field[nextPosition] = 1;
  64.   }
  65.  
  66.   console.log(field.join(" "));
  67. }
Advertisement
Add Comment
Please, Sign In to add comment