Searching for the subsequent location in a 2D array relative to the current position

Let's imagine we have a 3x4 array:

const arr = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
. If we provide the input as
["straight", "right", "left"]
, the starting position being arr[0][0] and initial direction as "east".

[
 [1,  2,  3,  4],
 [5,  6,  7,  8],
 [9, 10, 11, 12]
]

Starting from the initial position moving "straight" would result in 2. Next, taking a "right" turn should lead to 6, followed by making a "left" turn resulting in 7.

What is the JavaScript algorithm needed to achieve this?

Answer №1

  • Develop a mapping system that determines the next direction based on the current direction and movement.
  • For each movement, compute the subsequent direction, verify if it is valid, and then provide the following value, position, and direction. Continue this process for every move.
  • If an invalid move occurs at any point, an error will be thrown. You have the option to tailor the error handling to suit your requirements.

const nextDirMap = {
  north: { left: "west", right: "east", straight: "north" },
  south: { left: "east", right: "west", straight: "south" },
  east: { left: "north", right: "south", straight: "east" },
  west: { left: "south", right: "north", straight: "west" },
};

function getNextPos(grid, currPos, currDir, move) {
  const nextDir = nextDirMap[currDir][move];
  const [r, c] = currPos;
  const maxRowLength = grid.length;
  const maxColLength = grid[0].length;

  switch (nextDir) {
    case "north": {
      if (r <= 0) {
        throw "Unable to move";
      }
      return { val: grid[r - 1][c], pos: [r - 1, c], dir: "north" };
    }
    case "south": {
      if (r >= maxRowLength) {
        throw "Unable to move";
      }
      return { val: grid[r + 1][c], pos: [r + 1, c], dir: "south" };
    }
    case "east": {
      if (c >= maxColLength) {
        throw "Unable to move";
      }
      return { val: grid[r][c + 1], pos: [r, c + 1], dir: "east" };
    }
    case "west": {
      if (c <= 0) {
        throw "Unable to move";
      }
      return { val: grid[r][c - 1], pos: [r, c - 1], dir: "west" };
    }
  }
}

function solution(grid, initPos, initDir, moves) {
  let currPos = initPos;
  let currDir = initDir;
  let currVal;
  moves.forEach((move) => {
    let { val, pos, dir } = getNextPos(grid, currPos, currDir, move);
    currDir = dir;
    currPos = pos;
    currVal = val;
  });
  return currVal;
}

const res = solution(
  [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
  ],
  [0, 0],
  "east",
  ["straight", "right", "left"]
);

console.log(res); // 7

It should be noted that this solution presupposes the existence of a valid grid with consistent column numbers across all rows, and there must be at least one row present.

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

Exploring the process of sending post data and navigating to a URL using AngularJS

I am working on an application using angularjs 1.6 and Java 8. My goal is to send POST data to another application and navigate to the URL that this external application determines. The purpose of my application is to transmit data about a citizen who wan ...

What is the best way to ensure the constant rotation speed of this simple cube demo?

Currently delving into the world of Three.js. I'm curious about how to make the cube in this demo rotate at a consistent speed rather than depending on mouse interactions. Any tips on achieving this? ...

Launching in an Angular reactive form

When working with Angular reactive forms, I am facing an issue where I want to set a form control value using a property from a service. However, upon submitting the form, the value of the form control does not reflect the expected property value from the ...

Discovering an npm module within an ember-cli addon component

I recently encountered an issue while using ember-browserify to locate npm modules in my ember-cli applications - it seems to not function properly for ember-cli addons. This leads me to wonder: Are there alternative methods for importing npm modules into ...

Iterate through a jQuery function to retrieve values from checkboxes starting from the 4th one that has been clicked

I am currently using a loop in a form to calculate the total price of a product based on user selections. However, I have encountered a challenging task where certain checkbox groups have specific rules. For instance, group A should only contribute to the ...

Determining whether a mouse click occurred in the left or right side of a DIV element

Is there a way to determine whether a mouse click occurred on the left or right side of a div element? I'm curious about calculating this: $("div").click(function(e){ // code to calculate left or right half }); <div>Content that can change&l ...

The Skeleton-Avatar and ImageButton components in MUI React have had their backgrounds reshaped into perfect ovals

I am facing an issue with the mui Stack where all the background shapes of the Skeleton Avatar and background area are turning into oval or ellipsoid shapes. I have tried setting equal width and height for Avatar but it has not solved the problem. Is ther ...

Locate the textbox that pertains to the element currently in focus

My HTML is structured as follows: <tr> <td colspan="2" class="borderBottomCell"> <div class="benefitInfo" style="WIDTH: 99%! important;"> <asp:DropDownList ...

Error message in Linux for NodeJS global NPM package: "File or directory does not exist"

After setting up my Ubuntu 14.04 system, I installed nodejs and npm using the command: sudo apt-get install nodejs npm To ensure packages utilize the node interpreter instead of nodejs, I created a symlink with: sudo ln -s /usr/bin/nodejs /usr/local/bin ...

Ways to retrieve the length of a list received from a controller using the onChange() method in JQuery

In my Controller class, I am returning a list of players. httpReq.setAttribute("playersList", playersList); Now, in the onchange() method, I need to find out the size of this list. $('#teams').on('change', function(){ // code to get ...

Extracting multiple values using the .find method in JQUERY / JavaScript

I'm facing an issue with my JSP page form. When I submit the form, it generates a JSON string which is sent via AJAX post. The problem arises when I try to extract multiple values from the form using the following method: .find('input[name=ite ...

Is it better to compare columns, arrays, and lists using SQL, Numpy, or Python lists? Could Intertools be a faster and more efficient option?

My SQL database consists of two tables: Table tModel has 9 columns (ID, Date N1, N2, N3, N4, N5, N6, Flag) and a staggering 300 million rows Table tPairAP has 3 columns (ID, N1, N2) and only 750 rows The task at hand is to find rows in tModel where any ...

PHP trigger update query to modify table data on click event

I specialize in creating system notifications and have encountered an issue. My goal is to update the 'notifications' table from 'new=1' to 'new=0' for a logged-in user after a click event. How can I achieve this database up ...

jQuery DataTable error: Attempted to set property 'destroy' on an undefined object

<script> $('#archiveTable').DataTable({}); </script> <table id="archiveTable" datatable="ng" class="table table-sm" style="color:black"> <!--some code--> </table> This is a snippet of HTML code Upon checking t ...

Retrieve information from a JSON document

My project involves a bookStore with a list of books that I am working on. I am trying to extract all the book data from a JSON file and display them in a card view on a webpage. Although my code is error-free and seems to be functioning properly, the da ...

Purging the JavaScript output

Currently, I am calling an API and receiving a list of results. These results are then processed into an object for iteration and display. Below is the function responsible for this process: var getAvailability = () => { if (chosenData.hot ...

Guide to extracting information from a Node.js http get call

I am currently working on a function to handle http get requests, but I keep running into issues where my data seems to disappear. Since I am relatively new to Node.js, I would greatly appreciate any assistance. function fetchData(){ var http = requir ...

Having trouble getting the jQuery script to properly check file size in an HTML form before uploading?

I've created an HTML form with a jQuery script to verify the file size when the SAVE button is clicked. Despite my efforts, the check doesn't seem to be functioning properly in the HTML Form. Please assist me with this and thank you in advance ...

The ng-click method on the checkbox input field in AngularJS is not being triggered

I'm trying to trigger a function in a toggle switch using ng-click, but the customerActiveDeactive function isn't being executed. <a title="Active/ Deactivate" > <input type="checkbox" class="js-switch" ng-init="status=True" ng-model ...

Is there a way to transform an HTML table into an Excel file with several sheets?

Is there a way to transform multiple HTML tables into an Excel file with multiple worksheets? I need assistance with this task. You can find an example here function exportTablesToExcel() { var tableContent = "<table border='2px'>< ...