Closed HenryWilder closed 11 months ago
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);
}
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;
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;
}
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.
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)
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.
Tests have passed. Closing the issue.
The extension is not correctly recognizing Pythagorean Triples.
Examples:
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.