Finding the difference or sum within an array to identify the two numbers that produce a new array

In order to clarify, I am looking for a method to identify the two smallest numbers in a sorted array that will result in a specific number when subtracted. The process can be broken down into the following steps:

  • Iterate through the array and designate a current value from which other numbers will be subtracted.
    • Continue this process until you find the numbers that match the desired result, then return them.
For example, let's say we are looking for two numbers that, when subtracted from the array, result in 2.
Let givenArray = [1, 4, 8, 10];
The subtraction would proceed as follows: 4 - 1 = 3 (no match); // continue
                                           8 - 4 = 4 (no match); // continue
                                           8 - 1 = 7 (no match); // continue
                                           10 - 8 = 2 (match found); // stop and return 8, 10.

NOTE: It is possible that the same array may contain both 6 and 8 or 8 and 10, either of which results in 2. However, if both are present, 6 and 8 should be returned. The exact method used to generate the array is not crucial.

P.S: I was able to solve this issue yesterday, but I welcome any additional suggestions on how to approach it.

Answer №1

This clever solution harnesses the power of a hash table and employs a single-loop strategy to extract two values from an array in order to achieve balance.

To begin, calculate the absolute difference between the two values in arrayA and use this information to extract the values from the larger array.

Next, iterate through the larger array arrayB while checking for the presence of the required value and ensuring that the sum is smaller than any previously identified set.

The criteria for validation are based on the absolute difference between delta and v, where v represents the current array value, or by evaluating the sum of delta and v.

Lastly, to ensure the functionality of the process, the current value v is added to the hash table for future reference.

The outcome will be either an array containing two values that balance the original pair or undefined if no suitable values are found.

var arrayA = [3, 5],
    arrayB = [2, 9, 5, 4],
    delta = Math.abs(arrayA[0] - arrayA[1]),
    values = {},
    result = arrayB.reduce((r, v) => {
        function check(w) {
            if (!values[w] || r && r[0] + r[1] < v + w) return;
            r = [w, v];
        }
        check(Math.abs(delta - v));
        check(delta + v);
        values[v] = true;
        return r;
    }, undefined);

console.log(result);

Answer №2

It seems like there may be some confusion, but here is a potential solution for your issue:

const difference = arrayA[1] - arrayA[0];

let index1, index2;
for (index1 = arrayB.length - 1; index1 >= 1; index1--) { // Set the first value
    for (index2 = arrayB.length - 1; index2 >= 1; index2--) { // Set the second value
        if (index1 !== index2) {
            if (
                arrayB[index1] - arrayB[index2] === difference // Check subtraction
                || arrayB[index1] + arrayB[index2] === difference // Check addition
            ) return [arrayB[index1], arrayB[index2]];
        }
    }
}

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

Ways to get a Discord bot to echo a message?

As a novice in the world of discord.js and bot creation, I am eager to implement a simple magic 8-ball inspired command. This command will allow users to ask the bot a question and receive a random answer in response. const commands = [ new SlashCommandBui ...

Appending a JSON object to an array does not result in the object being added to the

Can anyone help me with an issue I'm facing? I have a code snippet where I am trying to push a JSON Object into an array, but the array is not updating properly. It only shows the last pushed element. var myData = {}; var id = 0; $("a").on('cli ...

What is the best way to retrieve the directory path from a FileReader in Java

Hey there, check out these codes I have for reading the file that the user uploads: function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $('#myImg' ...

Tips on creating a slow and gradual border animation that unfolds smoothly

I am looking to create an animation effect on a border, gradually revealing it like in this Codepen example. However, my specific requirements are: The previous line should not be removed, but rather shown along with the new border. The border color ...

What is the process for retrieving an Object from $cookies?

I've encountered an issue where I'm storing a user object on a Cookie and, upon the client's return visit to the site, I want to utilize this object's properties. However, upon the client's return, my cookie object appears as [obj ...

Is there a way to obtain the current URL within the index.html file using Vue.js?

How can I retrieve the current URL in my index.html file using Vue.js? When using pure JavaScript in index.html, I am only able to obtain the URL of the initial page. In order to capture the URL of other pages, I need to refresh the page as the value of ...

attempting to fulfil a promise through a resolution

I am currently attempting to use a resolve with a promise in response to an issue with filters that I am currently tackling. However, my resolve function is not yet functioning as expected. I have decided to implement this approach based on advice I recei ...

The JQuery parseFloat() function seems to be consistently returning "NAN" whenever it is used with the .text property

I am currently encountering an issue with parsing the text property of an input element identified by the id currency-converter. My goal is to convert this text into a floating-point value so that I can proceed with applying mathematical operations to conv ...

What is the most effective method to retrieve the UserName using Javascript?

Can someone please explain to me the difference between using session["user"].name and session["user:name"]? // I don't understand why we have to put the user session into the JavaScript global space :( var session = { user: { "Id":"d675c ...

Tips for clearing a material-ui search input field with the help of a button

Currently, I am working on a tutorial that involves implementing react material-ui tables along with a search input textfield. I am attempting to enhance this by adding a button that not only resets the table report but also clears the search input textfie ...

What is the process for retrieving the value of `submit.preloader_id = "div#some-id";` within the `beforesend` function of an ajax call?

In my JavaScript code, I have the following written: var formSubmit = { preloaderId: "", send:function (formId) { var url = $(formId).attr("action"); $.ajax({ type: "POST", url: url, data: $(formId).serialize(), dataTy ...

There seems to be a connection issue between my Jquery and HTML, as they

I've hit a roadblock because my jQuery isn't connecting and I can't seem to figure out why. It's been stumping me for hours. Here is the HTML code snippet from exercise6.html: <!DOCTYPE html> <html lang="en> <h ...

What is the best way to interact with my component in React?

As a newcomer to Reactjs, I have a question regarding my current setup: The components in my project include navComponent.js, stackComponent.js, and nav.js I am trying to pass data from stackComponent.js to navComponent.js so that the nav.js data can be ...

Secure an input field for exclusive attention. React

How can I lock the focus of my input field? I attempted using the following code: onBlur={this.click()} However, it was not successful. What is the correct way to accomplish this? ...

Incorporate ng-model to manage dynamically generated HTML elements

I have created dynamic div elements with a button inside, and I want to access its value using ng-model, but the value is not being retrieved. Here is my code: var url = "/api/chatBot/chatBot"; $http.post(url,data) .success(function(data){ $scope.mes ...

Using jQuery Datepicker, showcase two distinct datepickers on a single page

Currently, I am utilizing the jQuery [Datepicker][1] on a website, but I am facing challenges when attempting to display two datepickers on the same page in different manners. The first one should only appear once you click the text box, and once a date i ...

I am experiencing issues with the middleware not functioning properly after implementing a custom application with Next.js

I'm currently diving into Next.js version 13 and attempting to customize the app based on the standard documentation. However, it seems that the middleware isn't being invoked as expected. I suspect there might be something wrong with my implemen ...

What is the process for executing PhantomJS commands through a NodeJs server?

My current challenge involves setting up a Node Server and incorporating PhantomJS commands within the NodeJS server. An example command includes: phantomjs phantom-server.js http://example.com Although I found some information related to this issue on ...

Attempting to execute npm install for an Odin project task, encountered the error "Module not Found". // A new error has surfaced, continue reading below

Trying to run npm install for the Odin Project JavaScript Fundamentals Part 4 lesson has been quite a challenge. Initially, upon forking and cloning the repository and running npm install as per the instructions, I encountered a permission error. However, ...

In JavaScript, promises remain in a pending state

How can I prevent my promises from remaining in the pending state and resolve them instead? var foundPeopleA = findPeopleA().then(function(result) { var res = [] result.map(function(el) { res.push(getProfileXML(el.sid)); ...