Skip to content

Instantly share code, notes, and snippets.

@don-smith
Forked from anonymous/index.html
Last active August 29, 2015 14:25
Show Gist options
  • Save don-smith/f862338446d2e4b2da69 to your computer and use it in GitHub Desktop.
Save don-smith/f862338446d2e4b2da69 to your computer and use it in GitHub Desktop.
/**
* Originally created in JS Bin: http://jsbin.com/yetubi/edit?js,console
* Dependencies: lodash
*
* This script finds 4 whole number values that have a specific relationship.
* Specifically, the sum of the squares of 3 numbers when they equal the
* square root of the 4th number. In linear algebra terms, this calculates
* the absolute value of a vector [x, y, z] when all values and the result
* are whole numbers. This formula is also known to calculate the distance
* of a 3D point from zero: d = sqrt(x*x + y*y + z*z)
*
* I recognize it's totally silly, but I wrote this because I was writing a
* unit test for a function that performs this calculation and I wanted my
* test cases to be whole numbers. This script is how I found them. I also
* thought this was a great little code kata in writing an algorithm.
*
* skip controls the smallest value in the vector
* start and stop control the range of distance, d
*/
console.clear()
const skip = 2
const start = 9
const stop = 100
var getNext = (arr, target, result) => {
if(arr.length === 0) return result
const current = _.last(arr)
result.push(current)
const next = target - current
const slice = _.filter(arr, (i) => { return i <= next })
return getNext(slice, next, result)
}
var getAnswer = (num) => {
const target = Math.pow(num, 2)
const square = (val) => { return Math.pow(val, 2) }
const squares = _.range(skip, num).map(square)
const maybe = getNext(squares, target, [])
const check = _.reduce(maybe, (total, i) => total + i)
if(maybe.length === 3 && check === target) {
console.log(num + ': '+ _.map(maybe, Math.sqrt))
}
}
_.range(start, stop).map(getAnswer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment