Fix bizarre bsearch/1 behaviour with a stream argument
This commit is contained in:
1 parent
d1a07cbdc1
commit
a1626adb7e
2 files changed
+8
-6
No files matched your search
+5
-5
@@ -224,10 +224,10 @@ def tostream:
|
|||||||
# the index of the target if the target is in the input array; and otherwise
|
# the index of the target if the target is in the input array; and otherwise
|
||||||
# (-1 - ix), where ix is the insertion point that would leave the array sorted.
|
# (-1 - ix), where ix is the insertion point that would leave the array sorted.
|
||||||
# If the input is not sorted, bsearch will terminate but with irrelevant results.
|
# If the input is not sorted, bsearch will terminate but with irrelevant results.
|
||||||
def bsearch(target):
|
def bsearch($target):
|
||||||
if length == 0 then -1
|
if length == 0 then -1
|
||||||
elif length == 1 then
|
elif length == 1 then
|
||||||
if target == .[0] then 0 elif target < .[0] then -1 else -2 end
|
if $target == .[0] then 0 elif $target < .[0] then -1 else -2 end
|
||||||
else . as $in
|
else . as $in
|
||||||
# state variable: [start, end, answer]
|
# state variable: [start, end, answer]
|
||||||
# where start and end are the upper and lower offsets to use.
|
# where start and end are the upper and lower offsets to use.
|
||||||
@@ -237,14 +237,14 @@ def bsearch(target):
|
|||||||
else
|
else
|
||||||
( ( (.[1] + .[0]) / 2 ) | floor ) as $mid
|
( ( (.[1] + .[0]) / 2 ) | floor ) as $mid
|
||||||
| $in[$mid] as $monkey
|
| $in[$mid] as $monkey
|
||||||
| if $monkey == target then (.[2] = $mid) # success
|
| if $monkey == $target then (.[2] = $mid) # success
|
||||||
elif .[0] == .[1] then (.[1] = -1) # failure
|
elif .[0] == .[1] then (.[1] = -1) # failure
|
||||||
elif $monkey < target then (.[0] = ($mid + 1))
|
elif $monkey < $target then (.[0] = ($mid + 1))
|
||||||
else (.[1] = ($mid - 1))
|
else (.[1] = ($mid - 1))
|
||||||
end
|
end
|
||||||
end )
|
end )
|
||||||
| if .[2] == null then # compute the insertion point
|
| if .[2] == null then # compute the insertion point
|
||||||
if $in[ .[0] ] < target then (-2 -.[0])
|
if $in[ .[0] ] < $target then (-2 -.[0])
|
||||||
else (-1 -.[0])
|
else (-1 -.[0])
|
||||||
end
|
end
|
||||||
else .[2]
|
else .[2]
|
||||||
|
|||||||
+3
-1
@@ -1427,8 +1427,10 @@ ascii_upcase
|
|||||||
"useful but not for é"
|
"useful but not for é"
|
||||||
"USEFUL BUT NOT FOR é"
|
"USEFUL BUT NOT FOR é"
|
||||||
|
|
||||||
bsearch(4)
|
bsearch(0,2,4)
|
||||||
[1,2,3]
|
[1,2,3]
|
||||||
|
-1
|
||||||
|
1
|
||||||
-4
|
-4
|
||||||
|
|
||||||
# strptime tests are in optional.test
|
# strptime tests are in optional.test
|
||||||
|
|||||||
Reference in new issue
Block a user