How to print all distinct 4 elements from an array that have the same given sum in Node.js

1 Answer

0 votes
function getDistinct4Elements(arr, sum) {
	arr.sort(function(a, b) {return a - b;});
    const size = arr.length;
    
    for (let i = 0; i <= size - 4; i++) {
        for (let j = i + 1; j <= size - 3; j++) {
         	const k = sum - (arr[i] + arr[j]);
            let fromstart = j + 1;
            let fromend = size - 1;
            while (fromstart < fromend) {
                if (arr[fromstart] + arr[fromend] < k) {
                    fromstart++;
                }
                else if (arr[fromstart] + arr[fromend] > k) {
                        fromend--;
                    }
                    else {
                        console.log(arr[i] + " " + arr[j] + " " + arr[fromstart] + " " + arr[fromend]);
                        fromstart++;
                        fromend--;
                    }
            }
        }
    }
}

const arr = [4, 8, 2, 5, 9, 0, 3, 7];
        
const sum = 18;

getDistinct4Elements(arr, sum);

  
  
  
  
/*
run:
  
0 2 7 9
0 3 7 8
0 4 5 9
2 3 4 9
2 3 5 8
2 4 5 7
  
*/

 



answered Aug 20, 2022 by avibootz
...