Advertisement
Guest User

Untitled

a guest
Jul 2nd, 2020
264
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function ladybugs(array) {
  2.     let workingArray = array.slice();
  3.     let fieldSize = workingArray.shift();
  4.     let bugsPosition = workingArray.shift().split(" ");
  5.     let finalBugsArray = [];
  6.    
  7.  
  8.     for (const position of bugsPosition) {
  9.         let currentBug = Number(position)
  10.         finalBugsArray[currentBug] = 1;
  11.     }
  12.     for (let i = 0; i < fieldSize; i++) {
  13.         if (finalBugsArray[i] === undefined) {
  14.             finalBugsArray[i] = 0;
  15.         }
  16.     }
  17.    
  18. for (let i = 0; i < workingArray.length; i ++) {
  19.     let [ladybugIndex, command, jumpLength] = workingArray[i].split(" ");
  20.    
  21.     ladybugIndex = Number(ladybugIndex);
  22.     jumpLength = Number(jumpLength);
  23.  
  24.     if (finalBugsArray[ladybugIndex] !== 1 || ladybugIndex < 0 || ladybugIndex >= finalBugsArray.length) {
  25.         continue;
  26.     }
  27.     // check for negative steps
  28.     if (jumpLength < 0) {
  29.         jumpLength = Math.abs(jumpLength);
  30.         if (command === 'right') {
  31.             command = 'left';
  32.         } else if (command === 'left') {
  33.             command = 'right';
  34.         }
  35.     }
  36.     // Free Position
  37.     finalBugsArray[ladybugIndex] = 0;
  38.     if (command === 'right') {
  39.         // Ladybug jumps one time
  40.         let newPosition = ladybugIndex + jumpLength;
  41.         // Jump another time if there is a lady bug
  42.         if (finalBugsArray[newPosition] === 1) {
  43.             newPosition = newPosition + jumpLength;
  44.         }
  45.         if (newPosition < finalBugsArray.length) {
  46.             finalBugsArray[newPosition] = 1;
  47.         }
  48.  
  49.     } else {
  50.         // Lady bug jumps to the left
  51.         let newPosition = ladybugIndex - jumpLength;
  52.         // Jump another time if there is a lady bug
  53.         if (finalBugsArray[newPosition] === 1) {
  54.             newPosition = newPosition - jumpLength;
  55.         }
  56.         if(newPosition >= 0 ){
  57.             finalBugsArray[newPosition] = 1;
  58.         }
  59.     }
  60.  
  61. }
  62.  
  63. console.log(finalBugsArray.join(' '));
  64.  
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement