Advertisement
bebo231312312321

Untitled

Feb 4th, 2024
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function ladyBugs(input) {
  2.   let fieldSize = input[0];
  3.   let ladybugPositions = input[1].split(' ').map(Number);
  4.  
  5.   let field = [];
  6.   for (let i = 0; i < fieldSize; i++) {
  7.     field.push(0);
  8.   }
  9.  
  10.   for (let x of ladybugPositions) {
  11.     if (x >= 0 && x < fieldSize) {
  12.       field[x] = 1;
  13.     }
  14.   }
  15.  
  16.   for (let i = 2; i < input.length; i++) {
  17.     // create directions
  18.     let [position, direction, flyTo] = input[i].split(' ');
  19.     position = Number(position);
  20.     flyTo = Number(flyTo);
  21.  
  22.     if (position < 0 || position > fieldSize || field[position] != 1) {
  23.       continue;
  24.     }
  25.     // negative steps reversal
  26.     if (flyTo < 0) {
  27.       flyTo = Math.abs(flyTo);
  28.       if (direction === 'right') {
  29.         direction = 'left';
  30.       } else if (direction === 'left') {
  31.         direction = 'right';
  32.       }
  33.     }
  34.     if (direction === 'right') {
  35.       field[position] = 0;
  36.       let newIndex = position + flyTo;
  37.      
  38.       while (newIndex < fieldSize) {
  39.         if (field[newIndex] === 1) {
  40.           newIndex += flyTo;
  41.           continue;
  42.         }
  43.         field[newIndex] = 1;
  44.         break;
  45.       }
  46.     } else if (direction === 'left') {
  47.       field[position] = 0;
  48.       let newIndex = position - flyTo;
  49.       while (newIndex >= 0) {
  50.         if (field[newIndex] === 1) {
  51.           newIndex -= flyTo;
  52.           continue;
  53.         }
  54.         field[newIndex] = 1;
  55.         break;
  56.       }
  57.     }
  58.   }
  59.   console.log(field.join(' '));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement