Skip to content

Instantly share code, notes, and snippets.

@hauntedhost
Created April 28, 2013 07:41
Show Gist options
  • Save hauntedhost/5476206 to your computer and use it in GitHub Desktop.
Save hauntedhost/5476206 to your computer and use it in GitHub Desktop.
nearest_larger
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
@manimal1
Copy link

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

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