Advertisement
Pijomir

Ladybugs

Sep 27th, 2023
928
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function playWithLadybugs(arr) {
  2.     let fieldSize = arr.shift();
  3.     let field = [];
  4.     for (let i = 0; i < fieldSize; i++) {
  5.         field.push(0);
  6.     }
  7.  
  8.     let ladyBugsPositions = arr.shift().split(' ').map(Number);
  9.     for (let position of ladyBugsPositions) {
  10.         if (position >= 0 && position < fieldSize) {
  11.             field[position] = 1;
  12.         }
  13.     }
  14.  
  15.     for (let el of arr) {
  16.         let [ladyBugPosition, direction, ladyBugMove] = el.split(' ');
  17.         ladyBugPosition = +ladyBugPosition;
  18.         ladyBugMove = +ladyBugMove;
  19.         if(ladyBugMove < 0) {
  20.             ladyBugMove = Math.abs(ladyBugMove);
  21.             direction = direction === 'right' ? 'left' : 'right';
  22.         }
  23.         if (field[ladyBugPosition] === 1) {
  24.             field[ladyBugPosition] = 0;
  25.             if (direction === 'right') {
  26.                 let newPosition = ladyBugPosition + ladyBugMove;
  27.                 if (field[newPosition] === 1) {
  28.                     newPosition = newPosition + ladyBugMove;
  29.                 }
  30.  
  31.                 if (newPosition < field.length) {
  32.                     field[newPosition] = 1
  33.                 }
  34.             } else {
  35.                 let newPosition = ladyBugPosition - ladyBugMove;
  36.                 if (field[newPosition] === 1) {
  37.                     newPosition = newPosition - ladyBugMove;
  38.                 }
  39.  
  40.                 if (newPosition >= 0) {
  41.                     field[newPosition] = 1
  42.                 }
  43.             }
  44.         }
  45.     }
  46.  
  47.     console.log(field.join(' '));
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement