Advertisement
Guest User

Untitled

a guest
Jan 28th, 2020
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(arr) {
  2.   // Take field size, fill the array with 0, take initial field values
  3.   const fieldSize = arr[0];
  4.   const fieldInit = Array(fieldSize).fill(0);
  5.   const initBugIndexes = arr[1].split(' ');
  6.  
  7.   // Fill the field with initial bugs
  8.   for (let i = 0; i < fieldSize; i++) {
  9.     let bugIndex = Number(initBugIndexes[i]);
  10.     if (bugIndex >= 0 && bugIndex < fieldSize) {
  11.       fieldInit[bugIndex] = 1;
  12.     }
  13.   }
  14.  
  15.   for (let i = 2; i < arr.length; i++) {
  16.     // Take index, direction, jump range from the array
  17.     let [bugIndex, direction, jumpRange] = arr[i].split(' ');
  18.     bugIndex = Number(bugIndex);
  19.     jumpRange = Number(jumpRange);
  20.  
  21.     // Checks if field space diff than 1, checks for negative bug index and higher index than possible field space
  22.     if (
  23.       fieldInit[bugIndex] !== 1 ||
  24.       bugIndex < 0 ||
  25.       bugIndex >= fieldInit.length
  26.     ) {
  27.       continue;
  28.     }
  29.  
  30.     // Checks jump range is negative, if so change directions
  31.     if (jumpRange < 0) {
  32.       jumpRange = Math.abs(jumpRange);
  33.       if (direction === 'right') {
  34.         direction = 'left';
  35.       } else if (direction === 'left') {
  36.         direction = 'right';
  37.       }
  38.     }
  39.  
  40.     // Bug move
  41.     fieldInit[bugIndex] = 0;
  42.     if (direction === 'right') {
  43.       // Bug moves one space right
  44.       let newPosition = bugIndex + jumpRange;
  45.       // Checks for second jump if there is another bug
  46.       if (fieldInit[newPosition] === 1) {
  47.         newPosition += jumpRange;
  48.       }
  49.       // Check for out field move
  50.       if (newPosition <= fieldInit.length) {
  51.         fieldInit[newPosition] = 1;
  52.       }
  53.     } else {
  54.       // Bug moves one space left
  55.       let newPosition = bugIndex - jumpRange;
  56.       // Checks for second jump if there is another bug
  57.       if (fieldInit[newPosition] === 1) {
  58.         newPosition -= jumpRange;
  59.       }
  60.       if (newPosition >= 0) {
  61.         fieldInit[newPosition] = 1;
  62.       }
  63.     }
  64.   }
  65.   console.log(fieldInit.join(' '));
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement