Determine the frequency of occurrences in an array where two elements are less than or equal to a specified sum - Using JavaScript

I've been working on a JavaScript function that counts the number of times two elements add up to a given sum. However, now I'm looking to modify this so that it not only considers when the two elements equal the sum, but also when they are less than or equal to the sum.

var array = [-10, -8, -1, 0, 1, 6, 10];
var sum = 16;

function findLessThanOrEqualSum(array, sum){
  var count = 0;
  var map = {};
  for(var i = 0; i<array.length; i++){
    var temp = sum - array[i]; //The current condition only handles cases when two elements equals the sum

    if(temp >= 0 && map[temp]){
      console.log(sum + " " + array[i] + " " + temp);
      count++;
    }
    map[array[i]] = true;
  }
  console.log(count);
}

findLessThanOrEqualSum(array, sum);

Is there a way to adjust the condition var temp = sum - array[i]; so that it includes instances where temp is less than or equal to sum - array[i];?

I attempted creating a second variable for temp to store values where temp <= sum - array[i];, but have had no luck. Any guidance would be greatly appreciated.

Answer №1

Why make things more complicated than they need to be? Simplify your approach by using nested loops that combine two elements from the array, then check if their sum is less than the target value.

var array = [-5, -4, 0, 3, 6, 9, 10, 12, 15];
var target = 20;

function findPairsLessThanTarget(array, target) {
  var count = 0;
  for (var i = 0; i < array.length - 1; i++) {
    for (var j = i + 1; j < array.length; j++) {
      if (array[i] + array[j] < target) {
        console.log(target + " " + array[i] + " " + array[j]);
        count++;
      }
    }
  }
  console.log("Number of pairs with sum less than target: " + count);
}

findPairsLessThanTarget(array, target);

Your current method may work fine when trying to find an exact match in a map, but when dealing with comparison conditions like finding sums less than a specific value, it's best to keep it simple and straightforward.

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

Incorporating tab navigation and drawer navigation in a React Native Expo application

I am encountering a warning in my react native expo app that uses react navigation 6. Even though I am able to display the tabs and the drawer, I keep getting this console alert: Found screens with the same name nested inside one another. Check Home, Home ...

Extracting Vertices, Edges, Faces, and Triangles from GLB Model Using ThreeJS GLTFLoader

I am looking to incorporate basic information about the model into my model viewer. Specifically, I need to obtain the vertex, edge, face, and triangle count of the object, or at the very least, the vertex count. My attempted approach involves using the f ...

I am interested in using the split method to separate and then mapping an object in JavaScript

Need assistance on separating an array using the split method. The array contains objects with properties such as name, course1, course2, and course3. Only the courses with text in their content along with a plus sign should be separated into an array usin ...

The issue of double submission persists, with the prevention of the default action

I'm in need of assistance. Within my form, I have two buttons displayed on the page: "Save" and "Publish". Below is the corresponding HTML code: <button type="submit" class="button">Save</button> <button type="button" class="button" n ...

Fill the table according to the selected criteria

One issue I am facing is that the table does not get cleared when using the arrow keys to navigate through select options. As a result, the data from the JSON is populated in sequence and does not match the currently selected option. Does anyone have any ...

generate a variety of react checkboxes based on a JavaScript object

I currently have an object in the state that holds the current value of four 'Risk Type' checkboxes riskTypes: {"Fraud": true, "Steal": true, "Scam": true, "Theft": true}, When rendering the subcomponent t ...

A variety of menu items are featured, each one uniquely colored

In the user interface I developed, users have the ability to specify the number of floors in their building. Each menu item in the system corresponds to a floor. While this setup is functional, I am looking to give each menu item a unique background color ...

When a function is transferred from a parent component to a child component's Input() property, losing context is a common issue

I have encountered an issue while passing a function from the parent component to the child component's Input() property. The problem arises when the parent's function is called within the child component, causing the this keyword to refer to th ...

Display a dialog box in jQuery UI 1.7 autocomplete when an item is selected

After implementing an autocomplete widget, I noticed that a dialog appears when an item is selected. However, I am struggling to get a specific field in the dialog to receive focus upon opening. Here is what I have attempted so far: //HTML <form actio ...

Obtain headers from receiving an external JavaScript file

I am trying to find a way to import an external .js file and access the response headers from that request. <script src="external/file.js?onload=callback"> function callback(data) { data.getAllResponseHeaders(); } </script> Unfortunately, ...

Using async and await for uploading images

I am trying to create a post and upload an image if one is provided. If I successfully upload the image, everything works smoothly. However, if I do not upload an image, I encounter the following error: UnhandledPromiseRejectionWarning: TypeError: Cannot r ...

Unexpected outcomes when generating jQuery pages using CSS

I have created a piece of JavaScript code that populates 3 divs with icons in even rows. However, I am facing an issue where my first two rows align as expected, but the third row starts aligned with .col-5. Can you help me troubleshoot this? function row ...

Using jQuery to generate a JSON object dynamically based on the values entered in each input field

I'm facing a situation where I need to extract data from a JSON format using PHP. However, I'm struggling with how to structure the Javascript object in order to dynamically create the JSON format. Here is my current scenario: <input title=" ...

Guide on incorporating a rating and review feature into your Windows 8 store app with JavaScript and HTML

Looking for assistance on integrating a rate and review feature into a Windows 8 store app using javascript and html. Specifically, I would like to add this option to both the charm settings and the app bar. When a user clicks on it, they should be directe ...

Slick.js integrated with 3D flip is automatically flipping after the initial rotation

I'm encountering an issue with my CSS3 carousel and 3D flipping. Whenever I navigate through the carousel and flip to the next slide, the first slide seems to automatically flip/flop after completing the rotation. You can see a visual demonstration o ...

PHP: Unresolved variations within an array's numerical values

After carefully crafting an array called $numbers, I managed to populate it with 45 unique numbers sorted from smallest to largest: $numbers = [5, 12, 24, 43, 60, 84, 87, 94, 124, 178, 226, 276, 313, 327, 336, 364, 367 , 368, 383, 399, 403, 434, 505, 539, ...

What is the process for adding elements to an object in Angular JS?

My goal is to send data to an ng-object after filling out and submitting an HTML form with user-defined values. However, after pressing submit, the values are being duplicated. I have attempted to clear the data by using $scope.user > $scope.user=&apos ...

Using three.js library from npm to import the THREE.Lut() functionality

After installing three packages from npm, I attempted to invoke: lut = new THREE.Lut( colorMap, numberOfColors ); However, I encountered the error message: "export 'Lut' (imported as 'THREE') was not found in 'three'. Altho ...

How to create a loop in Selenium IDE for selecting specific values from a drop-down list?

Is there a way to use Selenium IDE and JavaScript to test a drop-down box with specific items, not all of them, and continuously loop through until the entire list is covered? Any tips or recommendations on how to accomplish this? ...

"Comparing the integration of Javascript and CSS within an HTML file versus linking them from an

When it comes to including external javascript and CSS files, is there a noticeable difference compared to including all javascript and CSS files (including jQuery core) directly within the HTML file using <style>...</style> and <script> ...