Created
April 28, 2013 07:41
-
-
Save hauntedhost/5476206 to your computer and use it in GitHub Desktop.
nearest_larger
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
def nearest_larger(arr, idx) | |
diff = 1 | |
loop do | |
left = idx - diff | |
right = idx + diff | |
diff += 1 | |
if (left >= 0) && (arr[left] > arr[idx]) | |
return left | |
elsif (right < arr.length) && (arr[right] > arr[idx]) | |
return right | |
elsif (left <= 0) && (right >= arr.length) | |
return nil | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello Sean. First off, thanks for sharing. This is a very clever solution. However, it is flawed if you wish to meet the condition that you return the closest larger integer value nearest the idx value.
Ex.
arr = [1,2,6,3,4]
nearest_larger(arr, 3)
==> 4
But your code returns ==> 2