Skip to content

Instantly share code, notes, and snippets.

@runandrerun
Created November 25, 2018 17:09
Show Gist options
  • Save runandrerun/beb0d7d73ccfcdcf42070c8da1b3073a to your computer and use it in GitHub Desktop.
Save runandrerun/beb0d7d73ccfcdcf42070c8da1b3073a to your computer and use it in GitHub Desktop.
const closestEnemy = (arr) => {
let player = [];
let enemy = [];
let distance = 0;
let rowLength = arr[0].length;
let board = arr.length;
// iterate over the length of the board stored in arrWidth
for (let i = 0; i < board; i++) {
// split each row within the board into singlular elements
let row = arr[i].split("");
// set the length of each new split array for iteration
let rowLength = row.length;
for (let j = 0; j < rowLength; j++) {
// look for the player's starting position
// if the player (1) is found then push in the player's index
// && push the index of the row on the board into player array
if (row[j] == 1) {
player.push(j, i);
// look for every enemy (2) on the board
// if the enemy is found then push the enemy's index
// && the index of the row on the board into the enemy array
} else if (row[j] == 2) {
enemy.push(j, i);
}
}
}
for (let i = 0; i < enemy.length; i += 2) {
let newDistance = 0;
if (Math.abs(player[0] - enemy[i]) < rowLength / 2) {
newDistance = Math.abs(player[0] - enemy[i]);
} else {
newDistance = rowLength - Math.abs(player[0] - enemy[i]);
}
if (Math.abs(player[1] - enemy[i+1]) < board / 2) {
newDistance += Math.abs(player[1] - enemy[i+1]);
} else {
newDistance += board - Math.abs(player[0] - enemy[i]);
}
if (distance == 0 || newDistance < distance) {
distance = newDistance;
}
}
return distance;
}
closestEnemy(["0000", "1000", "0002", "0002"]);
closestEnemy(["0000", "2010", "0000", "2002"]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment