exploring a 2d grid with JavaScript for optimal routes

Hi there, I've been working on this problem for a few hours and I just can't seem to get 10 random test cases out of the 100 right.

If anyone could offer some help, it would be greatly appreciated. Here's the link to the problem:

Just a heads up, there might be a better way to solve the problem than what I came up with initially.

Code snippet:

function conquerIsland(map) {

  let path=[];
  let mar=[];
  let len=0,len1=0;


for(let i=1;i<8;i++)
{


 for( let j=0;j<i;j++)
 {

   if(map[j][i]=='u')
  { 

   if(len1===0 || len1==i+j)
   {
    path.push([j,i]);
    len1=i+j;
    }

  }
   if(map[i][j]=='u')
  {  

   if(len1===0 || len1==i+j)
   {
    path.push([i,j]);
    len1=i+j;
    }

  }


   if(map[j][i]=='m')
  { 
   if(len==0 || len==i+j)
   {
    mar.push([j,i]);
    len=i+i;
    }

  }


if(map[i][j]=='m')
  {  
    if(len==0 || len==i+j){
    mar.push([i,j]);
    len=i+j; 
  }
  }


  }
 if(map[i][i]=='m')
  {  
 if(len==0 || len==i+i)
 {
     mar.push([i,i]);
     len=i+i;
 }
 }
 if(map[i][i]=='u')
  {  
  if(len1==0 || len1==i+i)
  {
    path.push([i,i]);
    len1=i*2;
  }
  }
}
if(path.length>0)
{
if(path.length==1)
{ let path1;

path1 = [].concat.apply([], path);
return path1;

}

else
{
  path.sort(sortFunction);

function sortFunction(a, b) {
    if (a[0] === b[0]) {
        return 0;
    }
    else {
        return (a[0] < b[0]) ? -1 : 1;
    }
}
 return path;
}
}
else
if(mar!=[])
{
if(mar.length==1)
{ let mar1;

mar1 = [].concat.apply([], mar);
return mar1;

}
else
{
  mar.sort(sortFunction);

function sortFunction(a, b) {
    if (a[0] === b[0]) {
        return 0;
    }
    else {
        return (a[0] < b[0]) ? -1 : 1;
    }
}
   return mar;

}
}
else {
return [];
}
}

Answer №1

Take a look at the code snippet provided below with detailed comments to guide you through it:

function claimTerritory(map) {
    // an array to store all 'u's positions
    var uPositions = [];
    // an array to store all 'm's positions
    var mPositions = [];
    // our current position
    var currentPosition;
    
    for (var i = 0; i < map.length; i ++) {
        for (var j = 0; j < map.length; j ++) {
            if (map[i][j] == "u") {
                // found a 'u': add to uPositions array
                uPositions.push([i, j]);
            } else if (map[i][j] == "m") {
                // found an 'm': add to mPositions array
                mPositions.push([i, j]);
            } else if (map[i][j] == "p") {
                // found ourselves: update current position
                currentPosition = [i, j];
            }
        }
    }
    
    // determine which array to search from
    var searchArray;
    if (uPositions.length > 0) {
        searchArray = uPositions;
    } else if (mPositions.length > 0) {
        searchArray = mPositions;
    } else {
        // no 'u' or 'm', return empty array
        return [];
    }
    
    var minDistance = Infinity;
    var closestCoords = [];
    
    for (var i = 0; i < searchArray.length; i ++) {
        // calculate manhattan distance as there are no diagonals
        var distance = searchArray[i][0] - currentPosition[0] + searchArray[i][1] - currentPosition[1];
        
        if (distance == minDistance) {
            // multiple items with same shortest distance
            closestCoords.push(searchArray[i]);
        } else if (distance < minDistance) {
            // new shortest distance found, reset array
            minDistance = distance;
            closestCoords = [searchArray[i]];
        }
    }
    
    if (closestCoords.length == 1) {
        return closestCoords[0];
    }
    
    return closestCoords.sort(function(a, b) {
        // custom sorting logic
        for (var i = 0; i <= 1; i ++) {
            if (a[i] > b[i]) {
                return -1;
            }
            if (b[i] > a[i]) {
                return 1;
            }
        }
        return 0;
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show a distinctive value when the array contains more than 5 locations

I am trying to modify the following code snippet: <p class="country" data-country="UK">lon</p> <p class="country" data-country="UK">lon</p> <p class="country" data-country="UK">lon</p> <p class="country" data-country ...

What is the best way to incorporate progress updates into a rendered jade page?

I am currently working on a small express.js application with a form. When the form is submitted, it triggers a python script that takes approximately 5 minutes to run and outputs messages to the console while it is running. At the moment, I am able to cal ...

The performance of the Node echo server decreases significantly by a factor of 10 when utilizing stream pipes instead of buffering

When using node v8.1.4 and v6.11.1 I decided to start off with an echo server implementation called pipe.js or simply pipe. const http = require('http'); const handler = (req, res) => req.pipe(res); http.createServer(handler).listen(3001); ...

Using JavaScript to insert new rows into a table

Currently, I have a form with master-detail data. I've set up a table for the details and added rows using JavaScript upon button click. However, whenever I click the "Add Row" button, a new row is added momentarily before the page reloads, causing th ...

Utilizing Json data with Jquery for dynamically placing markers on Google Maps

Seeking assistance as I am currently facing a problem where I need to loop through JSON data and add it as markers on Google Maps, but unfortunately, it only returns null value. Is there a way to automatically connect this to JSON? My plan is to have a Gr ...

Issue with meta viewport on Android devices

Creating a versatile JavaScript dialog class is my current project using JQuery to generate centered div-popups on the screen. So far, implementation across common browsers has been straightforward. The challenge arises when dealing with mobile platforms ...

Capture keyboard input using socket.io

My goal is to capture individual keystroke events (keydown and keyup) in a chat client. The current code I have sets up a chat application that sends each message to a mongoDB cluster. However, I want to create a new record for each keystroke event rather ...

Is there a way to effectively redirect from the main path to another main path while still displaying subpaths?

import React from 'react'; import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom'; import Footer from './components/Footer'; import NavMenu from './components/NavMenu'; import ScrollToTop ...

Reading very large .csv files using the FileReader API in JavaScript with only HTML/jQuery can be accomplished by following these

Having trouble handling a large .csv file over 40 MB (with more than 20,000 lines) and displaying it as an HTML table. I'm developing a system using only pure HTML + JQuery. This is the format of my .csv worksheet: ================================== ...

Merging data sets with Javascript: A comprehensive guide

As a newcomer to the world of javscript, I'm faced with what seems like a simple question. I'm working with two datasets that contain a common column and I'd like to merge them together. The structure of the datasets is as follows: const da ...

Is there a way to link a number with a particular string and apply that string as a filter for iteration in AngularJS?

I've recently started learning AngularJS and I'm facing challenges with creating a reusable generic filter. Let's consider the colors, types, and list objects outlined in the new JSON below. I aim to develop a generic filter that can take t ...

jQuery Datatables causing hyperlinks to malfunction on webpage

After implementing jQuery datatables on this example using a PHP serverside processing file pulling data from MySQL, the Sign-in button used to work but now it just reloads the same index page. Manually typing in the address linked to the Sign In page work ...

Using Sscanf to parse a string entered through the command line

I'm encountering an issue with my project and despite searching for answers on forums, I have been unable to find a solution. struct time { int hours; int minutes; int seconds; char *format; }time1; int main(int argc, char *argv[]) { sscanf(argv[1], ...

I'd really appreciate your assistance in obtaining a value for a specific webelement

I am facing an issue where I am trying to retrieve the value from a WebElement 'input'. The general method getText() doesn't seem to work for me in this case. However, when I tried using JavaScript in the console, it worked perfectly: " ...

Is your HighCharts navigator and range scale malfunctioning?

Looking for assistance on limiting min and max values from a JSON array using JavaScript. I am facing an issue while working with Highstocks. The date is the first day in Unix, but the array contains the correct date. As a result, my navigator and range s ...

Errors in Compiling Dependencies for d3.js Using Typescript

Currently, I am in the process of developing a web application utilizing Node.js alongside Angular, Typescript, and d3.js, among other technologies. The application is functioning properly with library features working as expected. However, I am encounteri ...

What is the maximum storage capacity for variables on a NodeJS/ExpressJS server when handling multiple users?

As I delve into the node server code, I find myself pondering on the idea of storing temporary data - objects and arrays - within variables. These variables are housed in the client variable of a socket and are purged when connection with the client is l ...

What is the best way to send a parameter from JavaScript to a UserControl?

Within my ASP.Net application, I have a UserControl named EmployeesUserControl that is displayed within a JQuery modal dialog. Prior to displaying the Employees, I need to provide a filter criteria indicating which entity the employee belongs to. My query ...

Building an Organized jQuery Mobile App with PhoneGap

Currently, I'm developing a game in phonegap using the jQuery Mobile framework. As my project has progressed, I've noticed that my code has turned into a tangled mess of spaghetti with one HTML file and several JavaScript classes. I'm curio ...

Using JavaScript to access session data from the view in CodeIgniter

Working with CodeIgniter 2.0 Framework In my current project, I am facing a challenge where I need to access session data set up in the model from the view. Below is the code snippet that I have been testing within my view: <script type='text/ja ...