Determining an array index using two values

I was struggling to find the right words for the title.

In my scenario, I have two indexes in a 2D array (x and y) that need to be multiplied together to determine the index for a second array (1D). However, it's not a straightforward calculation because if either x or y is zero, the result will always be zero no matter what the other value is.

One way to solve this problem is by using nested loops as shown below:

    int count = 0;

for( int i = 0; i < x; i++ )
{
    for( int j = 0; j < y; j++ )
    {
        count++;
    }
}

//count now has the desired value

...but this solution seems very inefficient.

It feels like this should be a simple issue to resolve, and I've been avoiding asking about it until now, hoping it would turn out to be an easy fix.

Answer №1

To illustrate our point, let’s consider the data provided below:

let twoDimensionalArray = [[0,1,2],[3,4,5]];
let oneDimensionalArray = [0, 1, 2, 3, 4, 5];

If all subarrays possess equal lengths, one can easily determine the corresponding "row" in the 1-dimensional array by multiplying the index i with the length of each subarray and subsequently adding the "column" index.

However, this method is only applicable to matrices with fixed widths.

let subArrayLength = 3;
for (let i = 0; i < twoDimensionalArray.length; i++) {
    for (let j = 0; j < twoDimensionalArray[i].length; j++) {
        let oneDimensionalIndex = (subArrayLength * i) + j;
        console.log(twoDimensionalArray[i][j], oneDimensionalArray[oneDimensionalIndex]);
    }
}

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

Obtaining the client's IP address using socket.io 2.0.3: a comprehensive guide

Currently, I am facing a challenge using socket.io v2.0.3 in my node.js server as I am unable to retrieve the client's IP address. Although there are several suggestions and techniques on platforms like stackoverflow, most of them are outdated and no ...

How do I trigger a click event without actually selecting an option in selectpicker?

When I try to select an option from the dropdown menu using selectpicker, it doesn't get selected. For instance, clicking on the "two" option doesn't actually select it. How do I fix this issue with selectpicker? Here is the code snippet: ...

Can one use Javascript to access the Sharepoint REST API from an external source?

I'm looking to showcase the content of a Sharepoint list on an external webpage. I'm interested in using Javascript or PHP to make a REST call to Sharepoint for this purpose. Although I've researched Sharepoint's REST API, I'm uns ...

Identifying the relationship between child and parent components in Vue.js

I am new to Vue.js and I am practicing some simple exercises on communication between Vue components. However, I am struggling with understanding who is a child component and who is a parent component. For example, consider the following code snippet: HTM ...

Accessing API using Next.js 14

I am facing an issue with the following code which is written in next.js. The error displayed on the console is: GET http://localhost:3000/products/porducts.json 404 (not found) Additionally, I'm encountering this error: Uncaught (in promise) SyntaxE ...

Using Fetch API in NextJS requires pressing the Enter key twice for it to work properly

The functionality of this component should display JSON data in the console log after entering input into the search bar and hitting the enter key. However, there is a lag where the data doesn't show until the enter key is pressed a second time. Addit ...

Efficiently loading components with AngularJS, ocLazyLoad, and ui-router without consolidating all 'states' in the main app.js class

Having recently started using ui-router and ocLazyLoad, I encountered an issue that I couldn't resolve despite searching through various blogs. However, my app is currently functioning well with ocLazyLoad. In my main app.js configuration, I have the ...

Using Bootstrap 4 to Filter Cards by Title and Tag

I'm attempting to develop searchable cards using HTML, JavaScript, and Bootstrap 4, but I'm facing issues with my code. My goal is to filter these three cards using a search bar, based on their title (h5.card-title) and tags (a.badge). Below is ...

PHP looping through an array problem

I am facing an issue with an array that is displaying the following data: stdClass Object ( [firstName] => Rupert [headline] => Managing Director at READ Advisors [lastName] => Bowen-Jones [pictureUrl] => https://media.licdn.com/mpr/mprx/0_y ...

What are the steps for implementing alpha compositing using an array of RGBA data in numpy?

Utilizing this alpha blending formula to combine two color values, my goal is to extend this process to n numpy arrays of rgba image data. Although n will likely be relatively small (probably > 5) in practical use cases, all arrays will have the same sh ...

I am experiencing issues with the rendering of my q-btn elements in Quasar and they are

I recently started using Quasar and encountered an issue with my q-btn component buttons displaying white backgrounds at random, despite having added a background-color in the external stylesheets. Here are some examples of this perplexing problem: https ...

Javascript Macros for Mastering Excel

My goal is to use Javascript macros to handle excel spreadsheets instead of the standard VBA. I have found a way to run javascript code through VBA, as shown below: 'javascript to execute Dim b As String b = "function meaningOfLife(a,b) {return 42;}" ...

Tips for integrating JQuery into a JavaScript file seamlessly without causing conflicts

Similar Question: Dynamically Including jQuery using JavaScript if it's not already present I am currently working on a project that requires users to embed a piece of javascript code on their websites, similar to Google Analytics. My main concer ...

Alter the font color once the page has finished loading

Is there a way to change the color of the "View Results" text below? <script type="text/javascript" charset="utf-8" src="http://static.polldaddy.com/p/6352993.js"></script> <noscript><a href="http://polldaddy.com/poll/6352993/"> ...

Improving the App() function in React and Typescipt

When working on my React/Typescript app, I encountered a challenge with the length of the code in one of the sections. Despite watching tutorials and searching for solutions, I couldn't find a clear way to refactor it. The specific issue is with refa ...

Converting MySQL DateTime to seconds in JavaScript from PHP

In my JavaScript code, I have implemented a countdown timer that relies on two variables. The first variable, currentDate, is converted to milliseconds and then has 10 minutes worth of milliseconds added to it. The second variable, d, stores the current da ...

Changing color based on AngularJS condition using CSS

My HTML code looks like this: <div> <i class="glyphicon glyphicon-envelope" style="margin-top: -50px; cursor:pointer; color: #1F45FC" ng-click="createComment(set_id)"> </i> Route <center> ...

When you press the back button and navigate to a different page, the scroll position will remain unchanged

I'm facing an issue with scrolling on my angularjs app. Currently, the app consists of 2 pages: The first page displays a list of customers, where you can select one to view their details. The second page is a list of companies, following a similar s ...

What is the quickest way to redirect a URL in WordPress?

Is it possible to redirect a URL instantly in WordPress using this script code? JavaScript Code: jQuery(document).ready(function() { var x = window.location.href; if (x == 'http://example.com/') { window.location.hr ...

Troubleshooting navigation problems in AngularJS Bootstrap Navbar

Currently, I am working on integrating AngularJS with Bootstrap3 for a mobile application. In my index.html file, I have added a navbar (navbar-fixed-top) and there are forms loaded through partials/myform.html. However, when I scroll the page and a textbo ...