Last active
March 16, 2017 08:22
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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