Skip to content

Commit 2b7e75c

Browse files
committed
Fix findmax and findmin with iterables
The state is not guaranteed to be equivalent to the index of the element.
1 parent 3da9aee commit 2b7e75c

File tree

2 files changed

+25
-13
lines changed

2 files changed

+25
-13
lines changed

base/array.jl

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -821,36 +821,38 @@ function findmax(a)
821821
if isempty(a)
822822
throw(ArgumentError("collection must be non-empty"))
823823
end
824-
i = start(a)
825-
mi = i
826-
m, i = next(a, i)
827-
while !done(a, i)
824+
s = start(a)
825+
mi = i = 1
826+
m, s = next(a, s)
827+
while !done(a, s)
828+
i += 1
828829
iold = i
829-
ai, i = next(a, i)
830+
ai, s = next(a, s)
830831
if ai > m || m!=m
831832
m = ai
832833
mi = iold
833834
end
834835
end
835-
return (m, iterstate(mi))
836+
return (m, mi)
836837
end
837838

838839
function findmin(a)
839840
if isempty(a)
840841
throw(ArgumentError("collection must be non-empty"))
841842
end
842-
i = start(a)
843-
mi = i
844-
m, i = next(a, i)
845-
while !done(a, i)
843+
s = start(a)
844+
mi = i = 1
845+
m, s = next(a, s)
846+
while !done(a, s)
847+
i += 1
846848
iold = i
847-
ai, i = next(a, i)
849+
ai, s = next(a, s)
848850
if ai < m || m!=m
849851
m = ai
850852
mi = iold
851853
end
852854
end
853-
return (m, iterstate(mi))
855+
return (m, mi)
854856
end
855857

856858
indmax(a) = findmax(a)[2]

test/arrayops.jl

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ for i = 1:3
306306
end
307307
@test isequal(a,findn(z))
308308

309-
#argmin argmax
309+
#findmin findmax indmin indmax
310310
@test indmax([10,12,9,11]) == 2
311311
@test indmin([10,12,9,11]) == 3
312312
@test findmin([NaN,3.2,1.8]) == (1.8,3)
@@ -316,6 +316,16 @@ end
316316
@test findmin([3.2,1.8,NaN,2.0]) == (1.8,2)
317317
@test findmax([3.2,1.8,NaN,2.0]) == (3.2,1)
318318

319+
# #14085
320+
@test findmax(4:9) == (9,6)
321+
@test indmax(4:9) == 6
322+
@test findmin(4:9) == (4,1)
323+
@test indmin(4:9) == 1
324+
@test findmax(5:-2:1) == (5,1)
325+
@test indmax(5:-2:1) == 1
326+
@test findmin(5:-2:1) == (1,3)
327+
@test indmin(5:-2:1) == 3
328+
319329
## permutedims ##
320330

321331
#keeps the num of dim

0 commit comments

Comments
 (0)