Find the robot matching the given query having [top, right, bottom, left] index of the nearest walls in a 2D array.
Find the robot matching the given query having [top, right, bottom, left] index of the nearest walls in a 2D array.
Uber Round 1 on 23.05.2023
Incomplete solution below:
// &----w// -&---w
// --ww-w
// --&--w
// --&w-w
// wall index: [top, right, bottom, left]
const query = [4,2,3,1];
// q = robot
// w = wall
const arr = [
/* 0 */ [' ', ' ', ' ', 'w', 'w'],
/* 1 */ [' ', 'q', ' ', 'w', 'w'],
/* 2 */ [' ', ' ', ' ', 'w', 'w'],
/* 3 */ ['w', ' ', 'q', 'w', 'w'],
/* 4 */ ['q', ' ', ' ', 'w', 'w'],
/* 0 1 2 3 4 */
];
function findRobot(arr = [], query = []) {
const maxRow = arr.length;
const maxCol = arr[0].length;
let robotIndexMapping = {};
// store walls found row wise
let wallsMapByRowIndex = {
// 0: undefined,
// 1: undefined,
// 2: undefined,
// 3: undefined,
// 4: undefined,
// 5: 5 // assume edge is the wall
};
// store walls found col wise
let wallsMapByColIndex = {
// 0: undefined,
// 1: undefined,
// 2: undefined,
// 3: undefined,
// 4: undefined,
// 5: 5 // assusme edge is the wall
};
wallsMapByColIndex[maxCol] = maxRow;
wallsMapByRowIndex[maxRow] = maxCol;
// find the nearest wall to the right and bottom: [right, bottom]
for (let i = maxRow; i > -1; i--) {
for (let j = maxCol; j > -1; j--) {
const element = arr[i]?.[j];
if (!element || element === 'w') {
wallsMapByRowIndex[i] = j;
wallsMapByColIndex[j] = i;
}
// Check if curr el is a robot
if (element === 'q') {
let positionOfRobot = '' + i + j;
robotIndexMapping[positionOfRobot] = [
wallsMapByRowIndex[i] ? wallsMapByRowIndex[i] - j : maxCol,
wallsMapByColIndex[j] ? wallsMapByColIndex[j] - i: maxRow
];
}
}
}
// [top, left]
// TODO: iterate over found robots instead all array elements
let _wallsMapByRowIndex = {};
let _wallsMapByColIndex = {};
_wallsMapByColIndex[-1] = -1;
_wallsMapByRowIndex[-1] = -1;
// find the nearest wall to the top and left: [top, left]
for (let i = -1; i < maxRow; i++) {
for (let j = -1; j < maxCol; j++) {
const element = arr[i]?.[j];
if (!element || element === 'w') {
_wallsMapByRowIndex[i] = j;
_wallsMapByColIndex[j] = i;
}
// Check if curr el is a robot
if (element === 'q') {
let positionOfRobot = '' + i + j;
// distance of nearest wall from the top
robotIndexMapping[positionOfRobot].unshift(_wallsMapByRowIndex[i] ? j - _wallsMapByRowIndex[i] : maxCol);
// distance of nearest wall from the left
robotIndexMapping[positionOfRobot].push( _wallsMapByColIndex[j] ? i - _wallsMapByColIndex[j] : maxRow);
}
}
}
console.log('Robots right bottom: ', robotIndexMapping);
}
findRobot(arr, query);
Comments
Post a Comment