Created
November 12, 2009 10:44
-
-
Save tonini/232797 to your computer and use it in GitHub Desktop.
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
# chop.rb | |
# zastav [@samueltonini] | |
#1 | |
def chop(v, arr) | |
return false if arr.empty? | |
min = 0 | |
max = arr.length - 1 | |
mid = (max + 1) / 2 | |
until mid < min | |
break if v > arr[mid] | |
if v == arr[mid]; return mid; else mid -=1 end | |
end | |
until max < mid | |
return false if v > arr[max] | |
if v == arr[max]; return max; else max -= 1 end | |
end | |
end | |
#2 | |
def chop(v, arr) | |
return false if arr.empty? | |
min = 0 | |
max = arr.length - 1 | |
mid = (max + 1) / 2 | |
arr[min, mid].reverse_each do |a| | |
if v > a | |
arr[mid, max].reverse_each do |aa| | |
return false if v > aa | |
return arr.index(aa) if v == aa | |
end | |
elsif(v == a) | |
return arr.index(a) | |
end | |
end | |
end | |
#3 | |
def chop(v, arr) | |
return false if arr.empty? | |
min = 0 | |
max = arr.length - 1 | |
mid = (max + 1) / 2 | |
(arr.values_at(min..mid)).reverse.detect do |i| | |
return arr.index(i) if i == v | |
break if v > i | |
end | |
(arr.values_at(mid..max)).reverse.detect do |i| | |
return arr.index(i) if i == v | |
return false if v > i | |
end | |
end | |
#4 | |
def chop(v, arr) | |
return false if arr.empty? | |
min = -1 | |
max = arr.length | |
while((p=(max-min)/2) != 0) | |
if p > 0 | |
p += min | |
max = p if v < arr[p] | |
min = p if v > arr[p] | |
return p if v == arr[p] | |
end | |
end | |
end | |
a = [1,3,2,4,5,8,14,9,7,10,11,24,20,2.3,80,-1,-3,55,66,43,23,15,51,76,13,17,81,98,91,94,18,92,25, 28,34, 41,49].sort | |
if !(v = chop(76, a)) | |
puts "No such value available in the array." | |
else | |
puts "Value is at index #{v}" # Value is at index 30 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment