Skip to content

Commit

Permalink
Merge pull request #4 from SynapticSage/next_and_prev
Browse files Browse the repository at this point in the history
Add searchsortednext and searchsortedprevious
  • Loading branch information
joshday committed Feb 18, 2023
2 parents 2f58809 + c043ff5 commit fd0276e
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/SearchSortedNearest.jl
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module SearchSortedNearest

export searchsortednearest
export searchsortednearest, searchsortednext, searchsortedprevious

# from: https://discourse.julialang.org/t/findnearest-function/4143/5
"""
Expand Down Expand Up @@ -28,4 +28,26 @@ function searchsortednearest(a, x; by=identity, lt=isless, rev=false, distance=(
return i
end

function searchsortednext(a, x; by=identity, lt=isless, rev=false, distance=(a,b)->abs(a-b))
i = searchsortedfirst(a, x; by, lt, rev)
if i == 1
elseif i > length(a)
i = length(a)
else
i = i
end
return i
end

function searchsortedprevious(a, x; by=identity, lt=isless, rev=false, distance=(a,b)->abs(a-b))
i = searchsortedfirst(a, x; by, lt, rev)
if i == 1
elseif i > length(a)
i = length(a)
else
i = i - 1
end
return i
end

end
30 changes: 30 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,34 @@ using Test
@test searchsortednearest(reverse(a), x, rev=true) == argmin(abs.(reverse(a) .- x))
end
end
@testset "searchsortedprev" begin
@testset "range" begin
A = sort(rand(-100:0.25:100, 20));
RNG=rand(-100:0.25:100, 20)
# @info "set = $A"
for rng in RNG
ind_method1 = searchsortedprevious(A, rng)
ind_method2 = searchsortedfirst(rng .<= A, true) - 1
# @info "test" rng
@test ind_method1 == ind_method2
end
end
@testset "groundtruth" begin
@test all(searchsortedprevious.([collect(0.25:1:10.25)], 1:10) .== collect(1:10))
end
end
@testset "searchsortednext" begin
@testset "range" begin
A = sort(rand(-100:0.25:100, 20));
RNG=rand(-100:0.25:100, 20);
for rng in RNG
ind_method1 = searchsortednext(A, rng)
ind_method2 = searchsortedfirst(rng .<= A, true)
@test ind_method1 == ind_method2
end
end
@testset "groundtruth" begin
@test all(searchsortednext.([collect(0.75:1:10.75)], 1:10) .== (1 .+ collect(1:10)))
end
end
end

0 comments on commit fd0276e

Please sign in to comment.