Skip to content

Commit

Permalink
Fix findmax and findmin with iterables
Browse files Browse the repository at this point in the history
The state is not guaranteed to be equivalent to the index
of the element.
  • Loading branch information
nalimilan committed Nov 22, 2015
1 parent 3da9aee commit 2b7e75c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 13 deletions.
26 changes: 14 additions & 12 deletions base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -821,36 +821,38 @@ function findmax(a)
if isempty(a)
throw(ArgumentError("collection must be non-empty"))
end
i = start(a)
mi = i
m, i = next(a, i)
while !done(a, i)
s = start(a)
mi = i = 1
m, s = next(a, s)
while !done(a, s)
i += 1
iold = i
ai, i = next(a, i)
ai, s = next(a, s)
if ai > m || m!=m
m = ai
mi = iold
end
end
return (m, iterstate(mi))
return (m, mi)
end

function findmin(a)
if isempty(a)
throw(ArgumentError("collection must be non-empty"))
end
i = start(a)
mi = i
m, i = next(a, i)
while !done(a, i)
s = start(a)
mi = i = 1
m, s = next(a, s)
while !done(a, s)
i += 1
iold = i
ai, i = next(a, i)
ai, s = next(a, s)
if ai < m || m!=m
m = ai
mi = iold
end
end
return (m, iterstate(mi))
return (m, mi)
end

indmax(a) = findmax(a)[2]
Expand Down
12 changes: 11 additions & 1 deletion test/arrayops.jl
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ for i = 1:3
end
@test isequal(a,findn(z))

#argmin argmax
#findmin findmax indmin indmax
@test indmax([10,12,9,11]) == 2
@test indmin([10,12,9,11]) == 3
@test findmin([NaN,3.2,1.8]) == (1.8,3)
Expand All @@ -316,6 +316,16 @@ end
@test findmin([3.2,1.8,NaN,2.0]) == (1.8,2)
@test findmax([3.2,1.8,NaN,2.0]) == (3.2,1)

# #14085
@test findmax(4:9) == (9,6)
@test indmax(4:9) == 6
@test findmin(4:9) == (4,1)
@test indmin(4:9) == 1
@test findmax(5:-2:1) == (5,1)
@test indmax(5:-2:1) == 1
@test findmin(5:-2:1) == (1,3)
@test indmin(5:-2:1) == 3

## permutedims ##

#keeps the num of dim
Expand Down

0 comments on commit 2b7e75c

Please sign in to comment.