HenryWilder / amitygxmod-calculator

A browser extension designed for Opera GX, made for helping with algebra
1 stars 0 forks source link

No combination of parameters displays as a Pythagorean Triple #6

Closed HenryWilder closed 11 months ago

HenryWilder commented 11 months ago

The extension is not correctly recognizing Pythagorean Triples.

Examples:

image

image

This is not an issue of the result being inverted, as the result continues to be false when the parameters are NOT a Pythagorean Triple.

image

HenryWilder commented 11 months ago

Function handling Pythagorean Triples testing

export const isPythagorean = (...values: number[]): boolean => {
    const last = values[-1];

    // a² + b² + c²      = 2c²
    // a² + b² + c² - c² = 2c² - c²
    // a² + b²           =  c²      (which defines pythagorean triple)
    return sumOfSquares(values) === monomialProduct(last, 2);
}

Relevant dependencies

export const sum = (...values: number[]): number => values.reduce((prev, x) => prev + x, 0);

export const dotProduct = (a: number[], b: number[]): number => {
    if (a.length !== b.length) throw new Error("Cannot dot product different size arrays");
    return sum(...a.map((a_i, i) => a_i * b[i]));
};

export const sumOfSquares = (v: number[]): number => dotProduct(v, v);

export const monomialProduct = (x: number, m: number): number => x * x * m;

Unrolled & simplified

const isPythagorean = (...values: number[]): boolean => {
    // Assumes that [-1] gets last element
    const last = values[-1];

    // (a²+b²)+(c²)
    const sumOfSquares = values.map(x => x * x).reduce((prev, x) => prev + x, 0);

    // Assumes that "2cc" is equivalent to "(c²)+(c²)"
    const doubleFinalSquared = (last * last * 2);

    // Assumes that "a²+b² = c²" is equivalent to "(a²+b²)+(c²) = (c²)+(c²)"
    return sumOfSquares === doubleFinalSquared;
}
HenryWilder commented 11 months ago

Testing with the following yields the expected results.

((a, b, c) => {
    return (a*a+b*b+c*c) === (c*c*2);
})(3,4,5)

However, testing with the following does not.

((values) => {
    const last = values[-1];
    const sumOfSquares = values.map(x => x * x).reduce((prev, x) => prev + x, 0);
    const doubleFinalSquared = (last * last * 2);
    return sumOfSquares === doubleFinalSquared;
})([3,4,5])

The problem must lie in the usage of the array functions.

HenryWilder commented 11 months ago

The following test produces expected results ([50, 50])

((a,b,c) => [a*a+b*b+c*c, [a,b,c].map(x => x * x).reduce((prev, x) => prev + x, 0)])(3,4,5)
HenryWilder commented 11 months ago

Ah. The following returns undefined.

[3,4,5][-1]

I really don't know why I didn't think to check that before implementing it. I'll fix this now.

HenryWilder commented 11 months ago

image

image

Tests have passed. Closing the issue.