Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function solve(arr) {
- let field = new Array(Number(arr[0])).fill(0);
- let ladyBugs = arr[1].split(' ');
- let command = [];
- let moves = 0;
- // Setting LadyBugs in initial positions
- for (let i = 0; i < ladyBugs.length; i++) {
- if (ladyBugs.length <= field.length) {
- field[i] = 1;
- }
- }
- // Putting commands in an array
- for (let i = 2; i < arr.length; i++) {
- command[i - 2] = arr[i].split(' ');
- }
- for (let i = 0; i < command.length; i++) {
- moves = Number(command[i][2]);
- ladyBug = Number(command[i][0]);
- if (command[i][1] === 'right' && command[i][2].includes('-')) {
- command[i][1] = 'left';
- Math.abs(command[i][2]);
- } else if (command[i][1] === 'left' && command[i][2].includes('-')) {
- command[i][1] = 'right';
- Math.abs(command[i][2]);
- }
- for (let j = ladyBug; j < field.length; j++) { // j is the current ladybug
- // if the command is right, the moves are less or equal than the field length and next index is empty
- if (command[i][1] === 'right' && field[j + moves] <= field.length && field[j + moves] === 1) {
- field[j] = 0;
- field[j + moves] = 1;
- break;
- } else if (command[i][1] === 'right' && field[j + moves] <= field.length && field[j + moves] === 1) {
- field[j] = 0;
- field[j + moves + 1] = 1;
- break;
- } else if (command[i][1] === 'right' && field[j + moves] <= field.length && field[j + moves + 1] === 1) {
- field[j] = 0;
- field[j + moves + 2] = 1;
- break;
- } else if (command[i][1] === 'left' && field[j - moves] >= 0 && field[j - moves] === 0) {
- field[j] = 0;
- field[j - moves] = 1;
- break;
- } else if (command[i][1] === 'left' && field[j - moves] >= 0 && field[j - moves] === 1) {
- field[j] = 0;
- field[j - moves - 1] = 1;
- break;
- } else if (command[i][1] === 'left' && field[j - moves] >= 0 && field[j - moves - 1] === 1) {
- field[j] = 0;
- field[j - moves - 2] = 1;
- break;
- }
- }
- }
- console.log(field.join(' '));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement