Pirate Island Conquer Part 1
JavaScript
var mapSize = 8;
var uninhabitedIslands = [],
marineIslands = [];
function conquerIsland(map) {
findIslands(map);
if (uninhabitedIslands.length == 1 && marineIslands.length == 0) {
return uninhabitedIslands[0];
} else if (marineIslands.length == 1 && !uninhabitedIslands) {
return marineIslands[0];
} else {
var marineSolutions = getClosest([], marineIslands, true);
var finalSolutions = getClosest(marineSolutions, uninhabitedIslands, false);
if (finalSolutions.length == 1) finalSolutions = finalSolutions[0];
return finalSolutions;
}
}
function findIslands(map) {
uninhabitedIslands = [];
marineIslands = [];
for (var x = 0; x < mapSize; x++) {
for (var y = 0; y < mapSize; y++) {
var coordinates = [x, y];
var currentChar = map[x][y].charAt(0);
if (currentChar == 'u') {
uninhabitedIslands.push(coordinates);
} else if (currentChar == 'm') {
marineIslands.push(coordinates);
}
}
}
}
function getDistance(coordinates) {
var x = coordinates[0], y = coordinates[1];
return x + y;
}
function getClosest(solutions, islands, marine) {
var minDistance = [999, 'm'];
for (let i = 0; i < islands.length; i++) {
var currentIsland = islands[i];
var distance = getDistance(currentIsland);
if (distance <= minDistance[0]) {
let previousMin = minDistance[1];
minDistance = [distance, marine ? 'm' : 'u'];
if (solutions[0] && distance == getDistance(solutions[0])) {
if (!marine && previousMin === 'u') {
solutions.push(currentIsland);
} else {
solutions = [currentIsland];
}
} else {
solutions = [currentIsland];
}
}
}
return solutions;
}
- javascript (Private)
- 5-kyu (Private)
- codewars (Private)
- answer (Private)