Advertisement
teofarov13

Untitled

Jan 30th, 2023
686
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 ladybugsPositions = arr[1]
  4.         .split(' ')
  5.         .map(Number);
  6.     let ladybugsArray = [];
  7.  
  8.     // fill the array with 0
  9.     for (let i = 0; i < sizeOfField; i++) {
  10.         ladybugsArray.push(0);
  11.     }
  12.     // mark starting ladybugs index
  13.     for (let i = 0; i < sizeOfField; i++) {
  14.         let ladybugIndex = ladybugsPositions[i];
  15.         if (ladybugIndex >= 0 && ladybugIndex < sizeOfField) {
  16.             ladybugsArray[ladybugIndex] = 1;
  17.         }
  18.     }
  19.  
  20.     for (let i = 2; i < arr.length; i++) {
  21.         // JS destructuring
  22.         let [ladybugIndex, command, jumpLength] = arr[i].split(' ');
  23.         ladybugIndex = +ladybugIndex;
  24.         jumpLength = +jumpLength;
  25.  
  26.         if (ladybugsArray[ladybugIndex] !== 1 || ladybugIndex < 0 || ladybugIndex >= ladybugsArray.length) {
  27.             continue;
  28.         }
  29.         // check for negative steps
  30.         if (jumpLength < 0) {
  31.             jumpLength = Math.abs(jumpLength);
  32.             if (command === 'right') {
  33.                 command = 'left';
  34.             } else if (command === 'left') {
  35.                 command = 'right';
  36.             }
  37.         }
  38.         // Free Position
  39.         ladybugsArray[ladybugIndex] = 0;
  40.         if (command === 'right') {
  41.             // Ladybug jumps one time
  42.             let newPosition = ladybugIndex + jumpLength;
  43.             // Jump another time if there is a lady bug
  44.             if (ladybugsArray[newPosition] === 1) {
  45.                 newPosition = newPosition + jumpLength;
  46.             }
  47.             if (newPosition <= ladybugsArray.length) {
  48.                 ladybugsArray[newPosition] = 1;
  49.             }
  50.  
  51.         } else {
  52.             // Lady bug jumps to the left
  53.             let newPosition = ladybugIndex - jumpLength;
  54.             // Jump another time if there is a lady bug
  55.             if (ladybugsArray[newPosition] === 1) {
  56.                 newPosition = newPosition - jumpLength;
  57.             }
  58.             if (newPosition >= 0) {
  59.                 ladybugsArray[newPosition] = 1;
  60.             }
  61.         }
  62.  
  63.     }
  64.  
  65.     console.log(ladybugsArray.join(' '));
  66.  
  67. }
  68. ladyBugs([5, '3',
  69.     '3 left 2',
  70.     '1 left -2']
  71. );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement