skip to Main Content

Given the following code to find Pythagorean Triples, why am I getting duplicates rather than excluding them with the While loop followed by the If condition?

var a, b, c, i, pyTrips, temp;
pyTrips = new Array();
temp = new Array();

for (a = 1; a <= 10; a++) {
    for (b = 1; b <= 10; b++) {
        with (Math) {
            c = sqrt(pow(a, 2) + pow(b, 2));
        }
        if (c % 1 == 0) {
            temp = a < b ? [a, b, c] : [b, a, c];
            i = 0;
            while (i < pyTrips.length && pyTrips[i] !== temp) {
                i++;
            }
            if (i === pyTrips.length) {
                pyTrips.push(temp);
            }
            console.log(pyTrips.toString());
        }
    }
}

I assume it’s the pyTrips[i]!==temp part that’s tripping things up, but I’ve checked and there’s no type casting or anything; the comparison is in fact between two arrays. So not sure why the While loop seems to make it to pyTrips.length every time.

3

Answers


  1. Javascript arrays are objects. Objects are compared by comparing their object references, NOT by comparing their contents.

    You can do this by using toString on both arrays:

    while(i<pyTrips.length && pyTrips[i].toString()!==temp.toString()){ i++; }
    
    Login or Signup to reply.
  2. Your assumption is correct, you cannot compare two arrays directly. When you compare two arrays using the === operator, it compares their references, not their content.

    One hacky way to solve this is to use toString(), convert the two arrays to string and then compare

    pyTrips[i].toString() !== temp.toString()
    

    Another way is to use a utility function which compares arrays

    const isEqualArr = (arr1, arr2) => {
        if (arr1.length !== arr2.length) {
            return false;
        }
    
        return arr1.every((ele, index) => ele === arr2[index]);
    };
    

    And then use it like

    !isEqualArr(pyTrips[i], temp)
    
    Login or Signup to reply.
  3. You can try clearing the array after each successful iteration:

    var a, b, c, i, pyTrips, temp;
    pyTrips = new Array();
    temp = new Array();
    
    for (a = 1; a <= 10; a++) {
        for (b = 1; b <= 10; b++) {
            with (Math) {
                c = sqrt(pow(a, 2) + pow(b, 2));
            }
            if (c % 1 == 0) {
                temp = a < b ? [a, b, c] : [b, a, c];
                i = 0;
                while (i < pyTrips.length && pyTrips[i] !== temp) {
                    i++;
                }
                if (i === pyTrips.length) {
                    pyTrips.push(temp);
                }
                console.log(pyTrips.toString());
                pyTrips = [];
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search