Create a function that iterates through an array to find the indexes of elements that meet a specific condition simultaneously

Imagine having an array of random numbers with a length of n. I am looking to develop a function that can iterate through the array and identify two (or more) indices that meet a specific criteria simultaneously.

For example:

 const arr = [12, 10, 2, 3, 17, 42, 56, 38]

Create a function that finds the two indexes where multiplying their elements results in the largest possible product. (In this case, 56 * 42 would be the correct answer)

I acknowledge that for this instance, simply multiplying the two largest elements will yield the desired outcome. However, in more complex scenarios there may be multiple conditions to consider and the array elements could have varying unknown values. My focus is on understanding the underlying principle behind the solution. If you can provide a resolution to this problem while outlining your thought process, it would be greatly appreciated.

Answer â„–1

If your accumulation function is stable, you can easily sort the array and return the indices of the two largest elements. However, if the stability of the accumulation function is unknown, you can calculate the function pairwise and note down the indices of the elements that generate a larger value than the current accumulated one.

This versatile function can tackle the issue with any accumulation functions provided as parameters:

const findHighestIndices = (values, accumlationFunction) => {
  let currentMaximum = -Infinity;
  let indices = [];
  for (let i = 0; i < values.length; i++) {
    for (let j = 0; j < values.length; j++) {
       if (i === j) continue; // we only want to compare DIFFERENT elements
       const cummulation = accumlationFunction(values[i], values[j]);
       if (cummulation <= currentMaximum) continue;
       currentMaximum = cummulation;
       indices = [i, j];
     }
   }
   return indices;
};


    const arr = [12, 10, 2, 3, 17, 42, 56, 38];

    console.log(findHighestIndices(arr, (a, b) => a * b));

When the parameter order in the accumulation function is not fixed, my implementation offers significant optimization potential by eliminating the need to iterate through both i and j elements.

Answer â„–2

Although not a JavaScript expert, here is a potential solution.

To find the maximum product of two elements in an array without using the same index twice, I would iterate over the list and test the condition for each combination of indices expected to satisfy the condition.

const arr = [12, 10, 2, 3, 17, 42, 56, 38]
var max = -Infinity;
var max_i = 0
var max_j = 0
for(var i=0; i< arr.length; i++) {
for(var j=0; j< i+1; j++){
if(i==j){
//skip this iteration
}
var mul = arr[i]*arr[j];
if (mul > max){max = mul;max_i = i; max_j = j}
}}

The indices that result in the maximum product are stored in variables max_i and max_j.

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

What are some strategies for developing an algorithm with linear time complexity, O(N)?

Here's a problem I came across on Codility. You can check out an example here. The challenge is to determine if there exists a point, P, in an array of N integers (where 0 <= N < 100,000) such that the sum of elements before P equals the sum of ...

Exploring ways to locate a specific text within a URL using nodeJS

Here is a simple code snippet with a problem to solve: var S = require('string'); function checkBlacklist(inputString) { var blacklist = ["facebook", "wikipedia", "search.ch", "local.ch"]; var found = false; for (var i = 0; i < b ...

What is the best way to make nodemon exclude everything except for a specified folder and file?

I've organized my files in the following structure: . ├── admin/ │ └── ... └── services/ ├── user/ │ ├── main.js │ └── model.js └── post/ ├── main.js └─┠...

There is an absence of the 'Access-Control-Allow-Origin' header on the requested resource despite its existence

Currently, I am working on developing an application using Django and Phonegap. While attempting to send an Ajax Request with the following function: <script> $.ajax({ url: "http://192.168.0.101/commerce/pro ...

AngularJS Metronic sidebar sub menu collapses after clicking and does not stay open

Upon clicking the sidebar, a brief appearance of the submenu followed by its immediate disappearance seems to be the core issue at hand. The fact that Layout.js (slideUp func.) is triggered twice feels nonsensical I meticulously combed through the settin ...

How to effectively use the LIKE statement in mysql with node.js

app.post('/like/:level/:name', function(req, res){ connection.query("SELECT * from books where " + req.params.level + " like '%" + req.params.name + "'%", function(err, rows, fields) { if (!err){ var row = rows; res.send(row); console.l ...

Trigger a click event on a nested Angular 13 component to remove a class from its grandparent component

In my Angular 13 project, I am working with 3 components: Child Component : Burger-menu Parent Component : Header Grand-Parent Component : app.component.html Within the burger-menu component, there is a close button. When this button is clicked, I want t ...

Using jQuery to highlight the navigation menu when a specific div scrolls into view

I have implemented a side navigation consisting of circular divs. Clicking on one scrolls you to the corresponding .block div, and everything functions correctly. However, I am now curious if it is feasible to highlight the relevant .nav-item div based on ...

Click to remove the accordion div

My query is regarding an accordion feature that I have implemented. <div id="accordion" class="accord"> <h2> <a href="#">Item1</a></h2> <div> Content1 </div> <h2 > &l ...

Is it possible for me to utilize the webAudio API in Chrome to connect to the local audio output stream?

Currently, I am working on audio analysis for a visualizer application running on my computer. I am wondering if there is a way to directly access the output audio data stream from the browser? For this project, I am using JavaScript along with the three ...

Ways to remove a row from a div element in JavaScript without relying on tables

Hey everyone, I'm looking for a way to delete a row within a div when a delete button is pressed using JavaScript. The catch is that I need to accomplish this without using a table, only with div elements. Can anyone provide a solution for me? func ...

Looking for a prerequisite for running this script?

Seeking assistance from a skilled Javascript expert. I specialize in template development and utilize a specific script to display my footer link in all the free templates I create. If someone attempts to remove the footer link, their site will be redirec ...

Toggle the visibility of a div element and smoothly scroll to it on the page

Upon clicking the form, my goal is to show or hide it and scroll down to view the form. The current code I have in place seems to work after the first click. However, on the initial click, it shows the form but fails to scroll down. Any insights on what I ...

Utilizing RSelenium for accessing a website built using the <td> element

My supervisor has tasked me with retrieving data from the China in-depth accident study database. Given my limited experience with HTML and javascript, I decided to utilize RSelenium and phantomjs to assist me in completing this task. Although I was able ...

Is it possible to edit YouTube images or embed YouTube iframes without needing an account?

Recently, I developed a YouTube video sharing system but have encountered some uncertainties. My approach involves extracting the YouTube ID and embedding it in an iframe (I wonder if YouTube permits this). To enhance the visual appeal of the posts, especi ...

Changes in query parameters on NextJS navigation within the same page do not activate hooks

When utilizing NextJS without SSR, I encountered an issue with basic navigation using different query parameters. Upon the initial arrival on the page/component, everything seems fine as the component gets mounted and URL params change accordingly. However ...

Is the page reloading automatically after updating the innerHTML content?

Trying my hand at creating a JavaScript/HTML page that automatically generates an audio player when provided with a URL. However, every time I click the generated button, the audio player is inserted but then disappears as if the page is refreshing. Here ...

Guide to spinning a CannonJS RigidBody

Has anyone found a way to rotate a CANNON.RigidBody object in CannonJS (the physics library)? I'm attempting to align the object's rotation with that of the camera, so they both face the same direction. I understand that I need to adjust the quat ...

Order associative array by values according to a different array

Hey there! I have a unique array structure that I'd like to share: array[ 0 => array[ 'id' => 1, 'name' => 'Test 1' 'classId' => 3 ], 1 => array[ & ...

Can we retrieve the CSS of an element?

Using Selenium's webdriverJS, I have automated tasks on an HTML5 page. To incorporate a CSS selector into a function, I had to rely on XPath for selecting elements: var complexXpath = "//*/div/a"; /* This is just an example */ var element = mydri ...