maymunskoa

LadyBugs (Arrays)

Mar 28th, 2020
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input) {
  2.   let size = Number(input.shift());
  3.   let field = [];
  4.   field.length = size;
  5.   field.fill(0);
  6.  
  7.   const isValidIndex = (index, arr) => {
  8.     return index >= 0 && index <= arr.length - 1;
  9.   };
  10.  
  11.   const success = (position, arr) => {
  12.     if (position < 0 || position >= size) {
  13.       return true;
  14.     } else if (arr[position] === 0) {
  15.       arr[position] = 1;
  16.       return true;
  17.     }
  18.     return false;
  19.   };
  20.  
  21.   let initials = input
  22.     .shift()
  23.     .split(" ")
  24.     .map(Number);
  25.   for (const index of initials) {
  26.     if (isValidIndex(index, field)) {
  27.       field[index] = 1;
  28.     }
  29.   }
  30.  
  31.   for (const line of input) {
  32.     let data = line.split(" ");
  33.     let start = Number(data[0]);
  34.     let direction = data[1];
  35.     let change =
  36.       direction.toLowerCase() === "right"
  37.         ? Number(data[2])
  38.         : Number(data[2]) * -1;
  39.     let position = start + change;
  40.     if (field[start] === 1) {
  41.       field[start] = 0;
  42.       while (!success(position, field)) {
  43.         position += change;
  44.       }
  45.     }
  46.   }
  47.  
  48.   console.log(field.join(" "));
  49. }
Advertisement
Add Comment
Please, Sign In to add comment