Skip to content

Instantly share code, notes, and snippets.

@iboss-ptk
Last active August 21, 2017 01:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iboss-ptk/f173f00bfadcf2b40699c613e0626545 to your computer and use it in GitHub Desktop.
Save iboss-ptk/f173f00bfadcf2b40699c613e0626545 to your computer and use it in GitHub Desktop.
const roundNum = (i, j) => Math.max(Math.abs(i), Math.abs(j))
const sumRange = n => (n * (n + 1)) / 2
const accumulateBy = f => n => f(sumRange(n))
const roundCircumference = n => 8 * n
const accumulateDistanceUpToRound = accumulateBy(roundCircumference)
const distanceOnOuterRound = (i, j) => {
const n = roundNum(i, j)
const [ moveRight, moveDown, moveLeft, moveUp ] =
[ n + j, n + i, n - j, n - i ]
const topRightTurn = moveRight + moveDown
const bottomLeftTurn = moveLeft + moveUp
const fullTopRightTurn = 4 * n
const isTargetOnTopRightArea = i < j
return isTargetOnTopRightArea
? topRightTurn
: fullTopRightTurn + bottomLeftTurn
}
export const unspiral = (i, j) => {
const n = roundNum(i, j)
return accumulateDistanceUpToRound(n - 1) + distanceOnOuterRound(i, j)
}
@dtinth
Copy link

dtinth commented Aug 20, 2017

I really like the naming of the variables in distanceOnOuterRound; it looks very clear what is going on.

However I think the name roundOf is not self-descriptive yet.

@iboss-ptk
Copy link
Author

iboss-ptk commented Aug 20, 2017

Ummmm, This is a tricky one. How about just roundNum ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment