Sum up all even numbers in an array using JavaScript

I have an array of numbers: [20,40,60,60,20]. The task is to find pairs of two numbers whose sum is divisible by 60. In this array, there are 3 such pairs: (20,40), (40,20), and (60,60).

However, when I implemented the code to achieve this, it returned 4 instead of 3.

function countPairs (array) {
  let count = 0;
  for (let i = 0; i < array.length-1; i++) {
    for (let j = 0; j < array.length-1; j++) {
      let a = array[i];
      let b = array[j];
      if (checkPair(a, b) && notSameIndex(i, j)) {
        count++;
      }
    }
  }
  return count;
}

function checkPair (a, b) {
  return Number.isInteger((a + b)/60);
}

function notSameIndex (x, y) {
  return x !== y ? true : false;
}

Can you spot what's causing the discrepancy in the result?

Answer №1

Commence the second iteration from i+1 as you've already covered the ith index in the initial loop; therefore, traverse from i+1 to the array's length. Make sure to run both loops until i < array.length, considering that you initiate from index 0.

function tallyPlayList (array) {
  let count = 0;
  for (let i = 0; i < array.length; i++) {
    for (let j = i+1; j < array.length; j++) {
      let a = array[i];
      let b = array[j];
      if (validatePlayTime(a, b) && eliminateDuplicates(i, j)) {
        count++;
      }
    }
  }
  return count;
}

function validatePlayTime (a, b) {
  return Number.isInteger((a + b)/60);
}

function eliminateDuplicates (x, y) {
  return x !== y ? true : false;
}
console.log(tallyPlayList([20,40,60,60,20]))

Answer №2

You've encountered 2 issues in your code:

  1. Ensure that you iterate through the entire array by using either
    (let i = 0; i < array.length; i++)
    or
    (let i = 0; i <= array.length - 1; i++)
  2. The inner loop should begin from the outer index + 1 to avoid checking every combination twice.

function countPlayList (array) {
  let count = 0;
  for (let i = 0; i < array.length - 1; i++) {
    for (let j = i + 1; j < array.length; j++) {
      let a = array[i];
      let b = array[j];
      if (checkPlayTime(a, b)) {
        count++;
      }
    }
  }
  return count;
}

function checkPlayTime (a, b) {
  return Number.isInteger((a + b)/60);
}

console.log(countPlayList([20,40,60,60,20]));

By the way, you can simplify return x !== y ? true : false; to just return x !== y;, as this value is already boolean.

Answer №3

You have the option to modify certain elements:

  • Start iterating from i + 1 to just before the length of the array,
  • Utilize a concatenated string value of the current pair,
  • Implement a Set to monitor visited pairs,
  • Adopt a different condition for checking sums and employ the remainder operator for obtaining the remaining value,
  • Include a check for already seen values,
  • Save an unseen pair in memory,
  • Finally, return the count of unique pairs.

function calculatePairCount(array) {
    let pairs = new Set;
        
    for (let i = 0; i < array.length - 1; i++) {
        for (let j = i + 1; j < array.length; j++) {
            let a = array[i],
                b = array[j],
                pair = [a, b].join('|');
                
            if ((a + b) % 60 === 0 && !pairs.has(pair)) {
                pairs.add(pair);
            }
        }
    }
    console.log(...pairs);
    return pairs.size;
}

console.log(calculatePairCount([20, 40, 60, 60, 20]));

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

Unraveling the mysteries of the spread operator in Javascript

Having trouble finding the right keyword to search for my issue, as I am confused about JavaScript or TypeScript spread operator behavior. I encountered this problem while working on a drag and drop function today, but let me provide a simple example. Imag ...

How can I use str.match to strip out the "$" symbol and display only the numerical value?

Check out this code snippet: value = str.match(/$(\d+)/); Take for instance, Example 1: HK$999 Result to Display = 999 Consider Example 2: HK$1,999.20 Displayed result = 1 (not the desired outcome) How can I show Example 2 as 1999? Thank you every ...

Using Puppeteer-cluster along with cheerio in an express router API results in an unexpectedly blank response

I am currently working on developing an API using express, puppeteer-cluster, and cheerio to extract anchor elements containing specific words that can be used as query parameters. My aim is to utilize puppeteer to capture dynamically generated elements as ...

CSS for when the mouse hovers over an element

Two php files and a js file are involved in this scenario. The issue at hand is that when the div is clicked, it navigates to a new page with an appended # to the URL, causing it to scroll to the specified comment ID. However, instead of scrolling to the c ...

Is there a way to substitute the function variable using JavaScript?

Is there a method to dynamically replace the variable 'abc' with 'cde' in HTML using JavaScript? For example, if I have the following code: <table width="150" border="0" cellspacing="0" cellpadding="2" id="productBox"> <tr> ...

Maintain a consistent header height with CSS even when using the calc() function

--dis: calc(var(--max-height) - var(--min-height)); /* @media large{--min-height:13rem}; @media small{--min-height:6.5rem}; --max-height:75vh; */ --percent: calc(var(--scroll-ani) / var(--dis)); /* in js: document.body.style = "--scroll-ani: ...

Having trouble with Angular NgbModal beforeDismiss feature?

My goal is to add a class to the pop up modal before closing it, and then have it wait for a brief period before actually closing. I've been trying to do this using the beforeDismiss feature in the NgbModalOptions options in Angular Bootstrap's d ...

Numerous HTML documents being uploaded to the server for a multitude of individuals

Currently, I am developing a game on a website where players create new rooms and are assigned specific roles with individual powers. Some players need to wait for input from others, creating a dynamic gameplay experience. Additionally, there are certain ...

Trouble with video element and css not updating as expected based on conditions

I'm currently developing a video gallery featuring multiple videos that play sequentially. My goal is to eliminate the play button once it's clicked and display controls instead. I've attempted to use useRef and useState within useEffect, bu ...

"Ensuring Proper Validation for Forms with JavaScript: A Step-by-Step Guide

Here is a sample Javascript form: <form id="loginForm" name="loginForm" action="/create_session/" method="post">{% csrf_token %} <table border="0" cellpadding="0" cellspacing="0" id="id-form"> <tr> <th valign=" ...

What is the best way to retrieve a response from a modal dialog using jQuery?

Is there a way to utilize an add-in such as simple-modal or the dialog add-in in the UI kit to achieve AJAX interaction with the server? I am looking for a solution that allows the modal to communicate with the server and return the result back to the ca ...

I'm wondering if there exists a method to arrange a multi-array in javascript, say with column 1 arranged in ascending order and column 2 arranged in descending order?

Here is an example of a randomly sorted multi-array: let arr = [[3, "C"], [2, "B"], [3, "Q"], [1, "A"], [2, "P"], [1, "O"]]; The goal is to sort it in the following order: arr = [[1, "O" ...

Performing create, read, update, and delete operations in AngularJS using a

Everything seems to be working fine with the CRUD operations in AngularJS. When I click on the submit button, the values are successfully submitted to the database. However, the changes are not immediately reflected on the view. I either need a separate bu ...

Can a module factory be invoked from a different JavaScript file?

I have two separate javascript files and I am trying to retrieve one from another. To achieve this, I have created a Module factory as shown below; var module = angular.module('test',[]); module.factory('$result', function() { va ...

"The issue mentioned earlier happened within the paragraph component" - Troubleshooting array mapping in React

Struggling to figure out why the mapping of array objects won't display correctly in the scrimba mini-browser. Although I can see the array object with console.log, nothing appears on the browser. Any ideas on what I might be missing? Thanks. import ...

How to include a for loop within an array as an element

Below is an illustration of the data available: $scope.allmovies[ {title:"Harry Potter", time:130}, {title:"Star Wars", time:155}, {title:"Lord of the Rings", time:250}, {title:"Goonies", time:125}, {title:"Fast and Furious", time:140} ]; var mostpopular ...

What is the method for implementing type notation with `React.useState`?

Currently working with React 16.8.3 and hooks, I am trying to implement React.useState type Mode = 'confirm' | 'deny' type Option = Number | null const [mode, setMode] = React.useState('confirm') const [option, setOption] ...

ajax stops working due to issues with xmlHttp.readysate

Having recently started working with AJAX, I encountered an issue with my script. Here's the code snippet: var xmlHttp = createXmlHttpRequestObject(); function createXmlHttpRequestObject() { var xmlHttp; if(windows.ActiveXObject) { ...

Query Mongo Db to locate and access a user's profile and retrieve comprehensive information on all their cards

Here is an example of a MongoDB User document: { "name":"steve", "email": "[email protected]", "password": "tnvddcnd", "cards": [{ "tags": "card", "user&qu ...

Error: The initial parameter must be a string, Buffer, ArrayBuffer, Array, or Array-like Object. An object type was passed in instead in CryptoJS

In my quest to encrypt and decrypt data in react-native, I embarked on using the crypto node module by incorporating it into my react native project through browserify. While attempting encryption with the code snippet provided below, an error surfaces sta ...