Skip to content

Instantly share code, notes, and snippets.

@armcknight
Last active March 16, 2017 08:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save armcknight/b07f6b01b1e01bb853925fd122a9ffad to your computer and use it in GitHub Desktop.
Save armcknight/b07f6b01b1e01bb853925fd122a9ffad to your computer and use it in GitHub Desktop.
Second attempt at snapping to angle intervals in Trgnmtry. This one works, and runs in linear time.
extension String {
func indexOfClosestSorted(toValue value: Degree) -> Int {
var smallestDifference = last!
var closestIntervalAngleIdx = 0
for i in 0 ..< count {
let closestValueCandidate = self[i]
var difference = fabs(closestValueCandidate - value)
if difference == 0 {
return i
}
if difference < 0 {
difference *= -1
}
if difference < smallestDifference {
smallestDifference = difference
closestIntervalAngleIdx = i
}
}
return closestIntervalAngleIdx
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment