function findBikesForPeople(grid) {
var rows = grid.length, cols = grid[0].length;
var bikes = [], people = [];
for (var row = 0; row < rows; row++) {
for (var col = 0; col < cols; col++) {
if (grid[row][col] === 'B') {
bikes.push({y: row, x:col});
}
if (grid[row][col] === 'P') {
people.push({y:row, x:col});
}
}
}
var combis = [];
for (var p in people) {
for (var b in bikes) {
var d = distance(people[p], bikes[b]);
combis.push({person:p, bike:b, distance:d});
}
}
combis.sort(function(a,b) {return a.distance - b.distance});
var hasBike = [], isTaken = [], assignment = [];
for (var c in combis) {
var person = combis[c].person, bike = combis[c].bike;
if (!hasBike[person] && !isTaken[bike]) {
assignment.push({person:person,
px:people[person].x, py:people[person].y,
bike:bike,
bx:bikes[bike].x, by:bikes[bike].y});
hasBike[person] = true;
isTaken[bike] = true;
}
}
return assignment;
function distance(a, b) {
return Math.abs(b.x - a.x) + Math.abs(b.y - a.y);
}
}
var grid = [['B', '_', 'P', '_', '_', '_'],
['_', '_', 'B', '_', '_', '_'],
['_', '_', '_', '_', 'B', '_'],
['_', '_', '_', '_', '_', '_'],
['P', 'B', '_', '_', '_', 'P'],
['_', '_', '_', 'P', '_', '_']];
document.write(JSON.stringify(findBikesForPeople(grid)));