JavaScript Program to Find a triplet such that sum of two equals to third element


We will be writing a JavaScript program that finds a triplet where the sum of two elements equals the third element. This program will be implemented using arrays and loop structures. We will be iterating through the array and checking for each element if the sum of two elements equal to the current element. If we find such a triplet, we will immediately return it. This program will be helpful in various mathematical computations where we need to find such triplets that follow a specific rule.

Approach

Here is one approach to solving the problem of finding a triplet such that the sum of two elements equals the third element in an array using JavaScript −

  • Loop through the array and for each element, subtract it from the sum of all other elements in the array.

  • Check if the difference obtained in step 1 is present in the array.

  • If the difference is found in the array, return the triplet.

  • Repeat steps 1 to 3 for each element in the array.

  • If no such triplet is found, return an appropriate message

Example

Here is a complete JavaScript program to find a triplet such that the sum of two elements equals to the third element −

function findTriplet(arr) {
   for (let i = 0; i < arr.length; i++) {
      for (let j = i + 1; j < arr.length; j++) {
         for (let k = j + 1; k < arr.length; k++) {
            if (arr[i] + arr[j] === arr[k]) {
               return [arr[i], arr[j], arr[k]];
            }
         }
      }
   }
   return "No such triplet found";
}
let arr = [1, 4, 45, 6, 10, 8];
let result = findTriplet(arr);
console.log(result);

Explanation

  • The findTriplet function takes an array as input and returns a triplet if the sum of two elements equals to the third element.

  • The function uses three nested loops to check every possible combination of three elements in the array.

  • The outermost loop i iterates through each element of the array.

  • The second loop j starts from the next element of i and iterates through the remaining elements of the array.

  • The third loop k starts from the next element of j and iterates through the remaining elements of the array.

  • For each combination of three elements arr[i], arr[j], and arr[k], the function checks if arr[i] + arr[j] === arr[k]. If this condition is true, it returns the triplet [arr[i], arr[j], arr[k]].

  • If no such triplet is found, the function returns the string "No such triplet found".

  • The program declares an array arr and calls the findTriplet function, passing arr as an argument.

  • The result of the function is stored in the result variable and logged to the console.

Updated on: 13-Mar-2023

147 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements