Calculate the separation between items within a two-dimensional array using Javascript

Given the input string: 923857614

This input can be represented in a matrix as follows:

9 2 3
8 5 7
6 1 4 

If we have a moving sequence like this: 423692, it means starting at point 4, moving to 2, then to 3, followed by 6, then 9, and finally reaching 2.

The task is to calculate the length of the path. Initially, the length starts at 0. If the next step is adjacent to the current position, add 1; otherwise, add 2.

Here's an attempt at solving it:

function computeRoadLength(keypad, movingSequence) {
  // build the matrix
 const arr = [[keypad[0], keypad[1], keypad[2]],
              [keypad[3], keypad[4], keypad[5]], 
              [keypad[6], keypad[7], keypad[8]]];
  let roadLength = 0;
  for (i = 0; i < movingSequence.length; i++) {
    // logic to calculate distance goes here
    if (arr[i] > arr[i+1]) roadLength = roadLength + 1;
    if (arr[i] < arr[i+1]) roadLength = roadLength + 2;
  }

  return roadLength;
}

computeRoadLength(923857614, 423692); // 2 + 1 + 2  + 2  + 1 = 8, should return 8

Answer №1

One way to approach this is by creating an object that stores the positions of all keypad values and then calculating the absolute difference between these positions.

When adding to the movingSequence, consider adding just one or at most two elements.

function calculateDistance(keypad, movingSequence) {
    const positions = {};
    
    for (let i = 0; i < keypad.length; i++) {
        positions[keypad[i]] = [Math.floor(i / 3), i % 3];
    }
    
    let totalDistance = 0,
        last = positions[movingSequence[0]];

    for (let i = 1; i < movingSequence.length; i++) {
        const
            item = positions[movingSequence[i]],
            sum = Math.abs(last[0] - item[0]) + Math.abs(last[1] - item[1]);
                
        totalDistance += Math.min(sum, 2);        
        last = item;
    }

    return totalDistance;
}

console.log(calculateDistance('923857614', '423692')); // 2 + 1 + 2 + 2 + 1 = 8

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 nested hash maps within JavaScript

Having some trouble with creating a nested hash map in JavaScript (js), similar to the example below: let rooms = {}; rooms[roomNum][personName] = somethings; However, I keep encountering an error when attempting this: TypeError: Cannot set property &apo ...

AngularJS - "Refrain from replicating items in a repeater"

I am facing an issue with creating HTML textarea elements for each member of an array. Despite consulting the AngularJS documentation and attempting different track by expressions, I am unable to render them. The problem arises when a user inputs the same ...

Using AngularJS to create dynamic expressions with ng-repeat

I am working on creating a dynamic page that will display different lists based on certain aspects. The arrays I am using have different variable names, and I have been struggling to use a dynamic ng-repeat expression to achieve this. Can anyone offer some ...

A way to effectively utilize a variable containing information retrieved from mongoDB is to pass it to another file, enabling access to the stored data within that variable

Is it possible to utilize a variable containing data from mongoDB in a different react component? This would allow us to access the fetched data from mongoDB stored in that variable. Here is the code for the file where data from mongoDB is fetched and sto ...

What is the functionality of Mongoose for handling multiple updates?

Array; arr=[ { id: [ '5e6e9b0668fcbc7bce2097ac', '5e6e9b0e68fcbc7bce2097af' ], color: [ 'a', 'b' ] } ] Models; const varyant = Models.varyant function; Promise.all( arr.map((item)=>{ return var ...

Leverage the generic types of an extended interface to simplify the creation of a shorthand type

Attempting to streamline my action shorthand that interacts with AsyncActionCreators. A function has been crafted to accept a React dispatch: Dispatch<T> parameter: const fetchProfileAction = actionCreator.async<void, Profile, any>('FETC ...

File not found: The specified file 'C:Self Project eact-shopper eact-shopperclientuildindex.html' does not exist

I followed the tutorial and startup code by Reed Barger exactly, but every time I try to run the server I encounter this error: Error: ENOENT: no such file or directory, stat 'C:\Self Project\react-shopper\react-shopper\client&bso ...

How to use PHP and JavaScript to update a location marker on Google Maps

I'm new to web development and in need of some help, please. I have a code that is supposed to update the marker location with coordinates retrieved from a database. <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AP ...

Is it possible to search and filter DataTables by Group?

I'm currently using DataTables to display a table with grouped data. The first column is an ID that doesn't need filtering. I have select inputs for users to filter the table, but since nobody needs to filter by ID, I want to provide options to f ...

Traverse a collection of nested objects containing arrays as their values

Consider the following object: { "apples": [ "one", "two" ], "oranges": [ "three", "four" ] } If I want to find the value four within this object, how can I do so efficiently? Would a loop work, like the one shown below? for (var ...

Iterating through the nested JSON causes an error when trying to set properties of undefined

My dataset is structured as a nested JSON, with the main object named bwaResult. Within this object, there are three primary groups: actBwa, fcBwa, and planBwa. Each of these groups contains yearly data and results that include years. I am trying to organi ...

Finding specific data within a nested HTML name array using either JQuery or JavaScript based on the second level key

Is there a way to target all input elements with names that contain 'pref[*][location][]' using a jQuery selector or JavaScript? Specifically, I want to retrieve those inputs based on the 'location' key in the second level. <input ty ...

Retrieve information from a variety of selected checkboxes

Is there a way to retrieve the values of check boxes that are generated dynamically? @ $db = mysql_connect("abc", "abc", ""); mysql_select_db("abc"); $strSQL = "SELECT * FROM student"; ...

Is it possible to pass a mongoDB object to all prototype functions in JavaScript/Node.js?

I am currently facing challenges while working with NodeJS and MongoDB. I am struggling to pass the mongoDB object between prototype functions within my code. Can someone provide guidance on how to effectively pass this object between prototypes? In the m ...

Submitting a form across controllers in AngularJS: What you need to know

<div ng-controller="ctrl1"> <form name="form1" ng-submit="submitForm()"> <input type="text" name="email" /> </form> </div> <div ng-controller="ctrl2"> <button> Submit </button> </div&g ...

Error: Attempted to access undefined property 'renderMenu' in a promise without handling it

I am looking to generate a dynamic menu based on the JSON data provided below: [ { "teamId": "10000", "teamName": "Laughing Heroes", "superTeamId": "", "createTime": "2017-06-25T06:07:45.000Z", "createUserId": null }, { "team ...

Guide on creating a readUInt16BE function in a Node.js environment

Looking to implement the readUint16BE function in node.js, here's how it is declared: buf.readUInt16BE(offset, [noAssert]) Documentation: http://nodejs.org/api/buffer.html#buffer_buf_readuint16be_offset_noassert This function reads an unsigned 1 ...

Is Socket.io exclusive to browsers?

Similar Question: Using socket.io standalone without node.js How to run socket.io (client side only) on apache server My website is hosted on a Linux server with shared hosting. Since I don't have the ability to install node.js, I am looking ...

The mobile devices are not showing my HTML website

I have implemented the following CSS link code on my website: <link rel="stylesheet" href="index_files/front.css" media="all" type="text/css" > Additionally, I have included the following code <meta name="HandheldFriendly" content="True"> & ...

AngularJS - ng-change does not trigger for checkbox that toggles the class "switch"

CSS Styling: <span style="color: blue;">Hello, World!</span> JavaScript Function: function showMessage(){ alert('Hello!'); } I tried to implement a span element with blue text color. However, the function that was supposed to ...