// You need to distract "Big Bertha" until you special squad arrives.
// The cannon always shoots at the pair of soldiers closest to each other.
// We can predict which pair of soldiers in danger and protect them.
// This function should find the pair of units with the minimum distance between them.
function findNearestPair(units) {
// These variables are used to store comparable value and results.
var minDistance = 9001;
var nearestPair = ["Nobody", "Nobody"];
// You need to check and compare all pairs of units.
// Iterate all units with indexes from 0 to 'units.length-1'.
for (var i = 0; i < soldiers.length; i++){
for (var j = i+1; j < soldiers.length;j++){
var distance = soldiers[j].pos.x - soldiers[i].pos.x;
if (distance < minDistance){
minDistance = distance;
nearestPair = [soldiers[i],soldiers[j]];
}
}
}
// Use an additional loop through indexes 'j'from 'i+1' to 'units.length'.
// Find the distance between the i-th and j-th units.
// If the distance less than 'minDistance':
// Reassign 'minDistance' with the new distance.
// Reassign 'nearestPair' to the names of the current pair of units.
hero.say(minDistance);
return nearestPair;
}
while (true) {
var soldiers = hero.findByType("soldier");
// We know when the cannon shoots.
if (hero.now() % 8 === 5) {
var pairOfNames = findNearestPair(soldiers);
// Say the soldier's names and wizards will protect them.
hero.say(pairOfNames[0] + " " + pairOfNames[1]);
}
}
код называет не двух ближайших солдатов.Кстати как точно найти дистанцию между ними?