Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Another way to get all combination of integers of an array Javascript

I want to iterate an array and find all pairs where their difference is 2

This is what i have so far:

var numberOfCases = 5;
var diff = 2;

var input = [1,5,3,4,2];

getPossiblepairs(input);

function getPossiblepairs(input){
    for(cmp in input){
        for(number in input){
            if((input[cmp] - input[number]) == diff){
                console.log("("+input[cmp]+","+input[number]+")");
            }
        }

    }
}

This works but i still feel guilty using two for loops as the bigO is O(n^2) Is this the only way to do this?

like image 346
ipalibowhyte Avatar asked Nov 30 '14 09:11

ipalibowhyte


1 Answers

You can do this in O(n log n). Sort the array then go through it in a single pass. Find the difference between the current element and each of the next two, printing out the pair if one is different by 2.

like image 186
Allen Luce Avatar answered Sep 27 '22 18:09

Allen Luce