Skip to content

Commit

Permalink
Merge pull request #69 from JuliaLang/sk/findlast
Browse files Browse the repository at this point in the history
backport findprev, findlast & tests
  • Loading branch information
StefanKarpinski committed Apr 21, 2015
2 parents 204652a + ad38b08 commit 2c91b7a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/Compat.jl
Original file line number Diff line number Diff line change
Expand Up @@ -310,4 +310,29 @@ else
import Base: Libc, Libdl
end

if VERSION < v"0.4.0-dev+2418"
function findprev(A, start)
for i = start:-1:1
A[i] != 0 && return i
end
0
end
findlast(A) = findprev(A, length(A))
function findprev(A, v, start)
for i = start:-1:1
A[i] == v && return i
end
0
end
findlast(A, v) = findprev(A, v, length(A))
function findprev(testf::Function, A, start)
for i = start:-1:1
testf(A[i]) && return i
end
0
end
findlast(testf::Function, A) = findprev(testf, A, length(A))
export findprev, findlast
end

end # module
17 changes: 17 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -238,3 +238,20 @@ let A, B, s
end
@test s == 210
end

# findlast, findprev
let a = [0,1,2,3,0,1,2,3]
@test findlast(a) == 8
@test findlast(a.==0) == 5
@test findlast(a.==5) == 0
@test findlast([1,2,4,1,2,3,4], 3) == 6
@test findlast(isodd, [2,4,6,3,9,2,0]) == 5
@test findlast(isodd, [2,4,6,2,0]) == 0
@test findprev(a,4) == 4
@test findprev(a,5) == 4
@test findprev(a,1) == 0
@test findprev(a,1,4) == 2
@test findprev(a,1,8) == 6
@test findprev(isodd, [2,4,5,3,9,2,0], 7) == 5
@test findprev(isodd, [2,4,5,3,9,2,0], 2) == 0
end

0 comments on commit 2c91b7a

Please sign in to comment.