Advertisement
Guest User

10. Ladybugs

a guest
Oct 7th, 2019
474
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(arr) {
  2.     let field = new Array(Number(arr[0])).fill(0);
  3.     let ladyBugs = arr[1].split(' ');
  4.     let command = [];
  5.     let moves = 0;
  6.  
  7.     // Setting LadyBugs in initial positions
  8.     for (let i = 0; i < ladyBugs.length; i++) {
  9.         if (ladyBugs.length <= field.length) {
  10.             field[i] = 1;
  11.         }
  12.     }
  13.  
  14.     // Putting commands in an array
  15.     for (let i = 2; i < arr.length; i++) {
  16.         command[i - 2] = arr[i].split(' ');
  17.     }
  18.  
  19.     for (let i = 0; i < command.length; i++) {
  20.         moves = Number(command[i][2]);
  21.         ladyBug = Number(command[i][0]);
  22.         if (command[i][1] === 'right' && command[i][2].includes('-')) {
  23.             command[i][1] = 'left';
  24.             Math.abs(command[i][2]);
  25.         } else if (command[i][1] === 'left' && command[i][2].includes('-')) {
  26.             command[i][1] = 'right';
  27.             Math.abs(command[i][2]);
  28.         }
  29.         for (let j = ladyBug; j < field.length; j++) { // j is the current ladybug
  30.             // if the command is right, the moves are less or equal than the field length and next index is empty
  31.             if (command[i][1] === 'right' && field[j + moves] <= field.length && field[j + moves] === 1) {
  32.                 field[j] = 0;
  33.                 field[j + moves] = 1;
  34.                 break;
  35.             } else if (command[i][1] === 'right' && field[j + moves] <= field.length && field[j + moves] === 1) {
  36.                 field[j] = 0;
  37.                 field[j + moves + 1] = 1;
  38.                 break;
  39.             } else if (command[i][1] === 'right' && field[j + moves] <= field.length && field[j + moves + 1] === 1) {
  40.                 field[j] = 0;
  41.                 field[j + moves + 2] = 1;
  42.                 break;
  43.             } else if (command[i][1] === 'left' && field[j - moves] >= 0 && field[j - moves] === 0) {
  44.                 field[j] = 0;
  45.                 field[j - moves] = 1;
  46.                 break;
  47.             } else if (command[i][1] === 'left' && field[j - moves] >= 0 && field[j - moves] === 1) {
  48.                 field[j] = 0;
  49.                 field[j - moves - 1] = 1;
  50.                 break;
  51.             } else if (command[i][1] === 'left' && field[j - moves] >= 0 && field[j - moves - 1] === 1) {
  52.                 field[j] = 0;
  53.                 field[j - moves - 2] = 1;
  54.                 break;
  55.             }
  56.         }
  57.     }
  58.     console.log(field.join(' '));
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement