I'm trying to speed up my loop because it's currently running way too slow. Any suggestions

In an attempt to find the index of the maximum element after left rotation, I have come up with a method. The idea is to rotate array 'a' based on another array called 'rotate'. Each element in the 'rotate' array determines how many times array 'a' should be rotated. For example, if the element is 2, then array 'a' will be rotated twice. During each iteration, the index of the maximum element in the rotated array is found and stored. However, the code execution is taking too long and the test times out eventually.

const a = [1, 2, 4, 3];
const rotate = [2, 1];

The expected output of getLargestItemIndices function would be an array like this:

[0, 1]

For the first iteration (2 rotations), the max value (4) is at index 0, and for the second iteration, the max value is at index 1.

let indices = [];
const getMaxValueIndex = (arr) => {
    const maxValue = Math.max.apply(Math, arr);
    return arr.indexOf(maxValue);
}

const rotateArray = (a, d) => {
    while (d) {
        a.push(a.shift());
        d--;
    }
    indices.push(getMaxValueIndex(a));
}

function getLargestItemIndices(a, rotate) {

    for (let index = 0; index < rotate.length; index++) {
        rotateArray(a.slice(), rotate[index]);
    }
    return indices;
}

Answer №1

Any tips on how I can optimize my loop for faster performance? It's currently running too slow.

In summary, you can significantly speed up your code by eliminating the rotateArray() function.

Here is a more detailed explanation:

To improve efficiency, consider breaking down your loop into smaller, more manageable parts. Start by creating a function that identifies the index of the largest item in the input array using just one for loop.

Once you have the starting index of the largest item, brainstorm ways to efficiently calculate its new position after a rotation of n positions. Repeat this process for each number in the rotate array.

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 a 16-bit integer from the response of an LWIP server

On the server side, I have implemented a loop that takes a 16-bit integer ranging from 0 to 639 and splits it into two 8-bit characters to populate a buffer of 1280 Bytes. The buffer is then sent via TCP-IP to the client. .c unsigned int data2[1000]; ch ...

What causes state variables in React Native to only be updated during hot reload?

The Situation Within my React Native application, I have implemented a tab navigator. Each tab contains a <Checkbox> component that reflects the state variable and can be toggled by user interaction. Here is an example of what the Checkbox component ...

Send JSON information using a POST request through the Fetch API and retrieve it on the Express backend server

Currently, I am in the process of learning Express and front-end JavaScript. My aim is to pass JSON data via a POST request using the Fetch API and then handle it on the backend with Express. The backend code I have written looks like this: const express ...

Error encountered when attempting to trigger a Bootstrap dropdown within a designated div

When using React JS, I encountered an issue when trying to trigger a dropdown that was nested inside a div with the class name "row". Initially, I placed the data-toggle and data-target attributes inside the div, like so: <div className="row"> < ...

What is the best way to prevent a command from being displayed in the terminal when using node-pty and xterm?

Currently, I am leveraging xterm.js, node-pty, and electron to create a node repl-like terminal similar to repl.it. In order to execute a file and display the output in the terminal, I am using the following code snippet: ptyProcess.write("vm.runInNewCont ...

Is there a way to personalize the appearance of Static File in nextjs?

Is there a way to customize the display of static files, particularly images? For instance, when accessing a static file on a website like this: Currently, it just shows a basic img element. Is it possible to dynamically add additional elements to that d ...

"Resolving the problem of populating an empty array with JSON

My JSON structure at the top level is set up like this: { "video": [], "messages": [], "notifications": [] } In the database output stored in a variable called "result," I have data that I want to add to the "vide ...

Differences between const and let when utilizing the require function

With io.js now offering ES6 support, you can finally take advantage of the powerful const and let keywords. While let is seen as the successor to var with added capabilities, what about const? We all know what "constant" means, but when is it best practice ...

AngularJS has encountered an issue with a route resolve promise that has not been completely resolved

I'm currently working on a simple task to manage user roles within routes. The goal is straightforward: Verify the role of the logged-in user on each route (using a resolve function to authenticate the user based on token or login credentials) Direc ...

Converting JSON to XML with a single row for each individual object using C#

Currently, I am in need of assistance with converting JSON objects into XML single rows for each object. The current conversion to XML is not meeting my desired outcome. Can someone help me with this task? Additionally, I only require specific fields and n ...

Tips for animating a clicked list item from its current location to the top position and simultaneously hiding all other list items

Is it possible to create a dynamic list where clicking on an item will move it to the top position using jquery animate and hide the rest of the list items simultaneously? $(document).ready(function() { $(".menu").click(function() { $("li").animat ...

Getting the value of a CSS Variable from Radix UI Colors with Javascript/Typescript: A step-by-step guide

Currently, I am attempting to dynamically retrieve the Radix Colors values in JavaScript. The reason for this requirement is that I generate these colors based on user input, resulting in values that are variable. As a result, I cannot hardcode the values. ...

Defining the flow and functionality

I'm currently attempting to define a function signature using Flow. I had anticipated that the code below would generate an error, but surprisingly, no errors are being thrown. What could be causing this issue? // This function applies another functi ...

Ways to Retrieve the Initial Object by its Index from the Specified Object Below

Is there a way to access FirstObj by index in TestCode[0].List? Any suggestions on the correct method to achieve this? 'TestCode':{ 'FirstObj':{ 'List':[ { year:2014 }, ...

issues with the functionality of bootstrap modal

I'm currently working on a project where I need to set up a modal popup using bootstrap. The website I'm working on is organized by departments, so the only part of the code that I have control over is the main body of the site. I have included t ...

Is there a way to extract the query string from a file in order to query the database using ExpressJS?

I am having trouble with this code snippet as it doesn't seem to be working properly. var content = fs.readFileSync('/home/diegonode/Desktop/ExpressCart-master/views/partials2/menu8xz.hbs', 'utf8' ); req.db.products.find( co ...

Determining the maximum value while omitting a specific value within a property of a nested object

I'm struggling with the specific iteration logic required here. The object structure is somewhat complex: var answers = { cat1: { q1: { "question": "Why?", "answer": "No", "points": 6 }, q2: { "questi ...

Tips for adding an id attribute to a child element using jQuery

Here is the code snippet that I am currently working with: <div> <span id="01"> </div> <div> <span id="02"> </div> I am trying to assign an ID to each div element based on their child span, but when using jQuery, s ...

Can I expect the same order of my associative array to be preserved when transitioning from PHP to Javascript?

While using PHP, I am executing a mysql_query with an ORDER BY clause. As a next step, I am going through the results to construct an associative array where the row_id is set as the key. After that, I am applying json_encode on that array and displaying ...

Looping through elements with jQuery's `each` method within another `

When using div containers in my code, I wanted to loop over them and then iterate through the items within each container. Instead of $('.stackContainer .stackItem').each(, I was looking for a solution like this: // setup stacks $('.stackC ...