Advertisement
Guest User

LadyBugs

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