Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function solve(arr) {
- // Take field size, fill the array with 0, take initial field values
- const fieldSize = arr[0];
- const fieldInit = Array(fieldSize).fill(0);
- const initBugIndexes = arr[1].split(' ');
- // Fill the field with initial bugs
- for (let i = 0; i < fieldSize; i++) {
- let bugIndex = Number(initBugIndexes[i]);
- if (bugIndex >= 0 && bugIndex < fieldSize) {
- fieldInit[bugIndex] = 1;
- }
- }
- for (let i = 2; i < arr.length; i++) {
- // Take index, direction, jump range from the array
- let [bugIndex, direction, jumpRange] = arr[i].split(' ');
- bugIndex = Number(bugIndex);
- jumpRange = Number(jumpRange);
- // Checks if field space diff than 1, checks for negative bug index and higher index than possible field space
- if (
- fieldInit[bugIndex] !== 1 ||
- bugIndex < 0 ||
- bugIndex >= fieldInit.length
- ) {
- continue;
- }
- // Checks jump range is negative, if so change directions
- if (jumpRange < 0) {
- jumpRange = Math.abs(jumpRange);
- if (direction === 'right') {
- direction = 'left';
- } else if (direction === 'left') {
- direction = 'right';
- }
- }
- // Bug move
- fieldInit[bugIndex] = 0;
- if (direction === 'right') {
- // Bug moves one space right
- let newPosition = bugIndex + jumpRange;
- // Checks for second jump if there is another bug
- if (fieldInit[newPosition] === 1) {
- newPosition += jumpRange;
- }
- // Check for out field move
- if (newPosition <= fieldInit.length) {
- fieldInit[newPosition] = 1;
- }
- } else {
- // Bug moves one space left
- let newPosition = bugIndex - jumpRange;
- // Checks for second jump if there is another bug
- if (fieldInit[newPosition] === 1) {
- newPosition -= jumpRange;
- }
- if (newPosition >= 0) {
- fieldInit[newPosition] = 1;
- }
- }
- }
- console.log(fieldInit.join(' '));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement