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

Unreachable prevState when utilizing the useState hook

I am currently working on a component where I need to capture the previousState of an element. However, no matter what I try, it keeps returning the initial value. This suggests that there is some re-rendering happening, causing it to constantly default to ...

Execute an AJAX call to remove a comment

Having some trouble deleting a MySQL record using JavaScript. Here is the JavaScript function I am trying to use: function deletePost(id){ if(confirm('Are you sure?')){ $('#comment_'+id).hide(); http.open("get","/i ...

AngularJS SmartyUI position not dynamically updating on SmartyStreets plugin

In my angularJS application, I am utilizing SmartyStreets' LiveAddress for address validation and autofilling two fields in a form. After the user submits the form, a message (either success or failure) is displayed in a div above the form. However, t ...

Oops, it seems like the project is missing a `pages` directory. Please kindly create one in the project root. Thank you!

Initially, my project setup looked like this: public .next src pages components assets next.config.js It was functioning properly, but I made a structural change to the following: public src client next.config.js jsconfig.json pa ...

Execute an AJAX post request to the identical PHP page (utilizing the Jquery Form Plugin)

I am in the process of developing a new web interface using JavaTMP, an AJAX-based admin template. After spending time understanding its functionality, I have created a page with a form to allow users to create projects within my software. Typically, creat ...

I wonder where the file from the HTML form download has originated

Recently, I've been experimenting with the developer tools in Chrome to observe the behavior of websites at different moments. It has proven useful in automating certain tasks that I regularly perform. Currently, my focus is on automating the process ...

Loading content from another webpage within a webpage using Ajax

I successfully implemented an Ajax chat in a PHP page and it was working perfectly. However, when I tried to integrate the chat into another page using a pop-up div (via CSS with z-index), I encountered some issues. Here is the code snippet: function sho ...

using http to handle a 404 error

This specific function is designed to fetch data under normal circumstances and to return a value of 0 in the event of a 404 error. function retrieveData(url) { if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); ...

Child component destruction triggers an ongoing digestion process

I am facing a strange issue within my AngularJS application. The error I'm encountering is the common $digest already in process error. Despite searching online and reviewing similar questions, none of the proposed solutions have resolved the issue. T ...

How come I can never seem to make it past the number 1?

My ultimate goal is to develop a program that can decipher a word search puzzle from a 2D array using pointers exclusively. In the main function responsible for executing the actual word search, I have integrated a while loop designed to continue as long a ...

How can I use the select2 jQuery plugin with the tags:true option to ensure that selected choices do not appear again in the dropdown menu?

Transitioning to select2 for tagging from a different plugin, I'm facing a gap that I need to address in select2's functionality. Let's consider an example. Suppose my list of choices (retrieved server-side via Ajax request) is: "Dog", "Ca ...

When an import is included, a Typescript self-executing function will fail to run

Looking at this Typescript code: (()=> { console.log('called boot'); // 'called boot' })(); The resulting JavaScript is: (function () { console.log('called boot'); })(); define("StockMarketService", ["require", "exp ...

My Angular Router is creating duplicate instances of my route components

I have captured screenshots of the application: https://ibb.co/NmnSPNr and https://ibb.co/C0nwG4D info.component.ts / The Info component is a child component of the Item component, displayed when a specific link is routed to. export class InfoComponent imp ...

Is there a way for me to gain entry to this array in vuejs?

Can anyone help me with accessing the objects in this array? I am using laravel, inertiajs, and vuejs. I am passing a variable from a laravel controller to a vuejs component with inertia.js. https://i.stack.imgur.com/p7yjL.png https://i.stack.imgur.com/y ...

Issue: Module 'curl' is not located at Function.Module._resolveFilename (module.js:489:15)

After installing node.js using the Windows installer, I noticed that the folder structure created was C:\Program Files\nodejs\node_modules\npm\node_modules. It seems like all the module folders are in the last node_modules director ...

Having trouble with installing Node Windows NPM?

I'm attempting to install a simple package in Node.js, but when I use the standard command, it indicates that it cannot find the file or directory (refer to the image below). Despite updating and re-installing npm, the issue persists. I am using Windo ...

Changing the structure of a JSON array in JavaScript

I'm currently developing an ExpressJS application and I need to send a post request to a URL. My data is being retrieved from a MS SQL database table using Sequelize, and the format looks like this: [ { "x":"data1", "y":& ...

Vue Method always executed (regardless of click event)

I'm fairly new to vue and still getting a grasp on the fundamentals of my code. Currently, I am facing an issue with a Method. It should only trigger when the user clicks on the button, but it seems to be triggered all the time. I even tried adding ...

Compatibility of HTML5 websites with Internet Explorer

Following a tutorial on HTML5/CSS3, I meticulously followed each step to create a basic website. While the demo of the site worked perfectly in Internet Explorer 8 during the tutorial, my own version did not display correctly when viewed in IE8. I discove ...

How can I display the most recent offcanvas opening at the top of the page?

The issue I'm facing is related to the offcanvas3 opening behind offcanvas2. It appears like this: $("#open-offcanvas2").on("click", function(){ $("#offcanvas2").offcanvas("show") }) $("#open-offcanvas1").on("click", function(){ $("#offcanvas1" ...