Skip to content

Commit 19a573b

Browse files
authored
Merge pull request #14 from lmshk/nthperm
nthperm! argument checking
2 parents 0e0edc6 + 54bd3ee commit 19a573b

File tree

2 files changed

+15
-5
lines changed

2 files changed

+15
-5
lines changed

src/permutations.jl

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -146,15 +146,15 @@ end
146146
In-place version of [`nthperm`](@ref); the array `a` is overwritten.
147147
"""
148148
function nthperm!(a::AbstractVector, k::Integer)
149-
k -= 1 # make k 1-indexed
150-
k < 0 && throw(ArgumentError("permutation k must be ≥ 0, got $k"))
151149
n = length(a)
152150
n == 0 && return a
153-
f = factorial(oftype(k, n-1))
151+
f = factorial(oftype(k, n))
152+
0 < k <= f || throw(ArgumentError("permutation k must satisfy 0 < k ≤ $f, got $k"))
153+
k -= 1 # make k 1-indexed
154154
for i=1:n-1
155+
f = div(f, n - i + 1)
155156
j = div(k, f) + 1
156157
k = k % f
157-
f = div(f, n-i)
158158

159159
j = j+i-1
160160
elt = a[j]

test/permutations.jl

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,17 @@ end
3838
#Euler Problem #24
3939
@test nthperm!([0:9;],1000000) == [2,7,8,3,9,1,5,4,6,0]
4040

41-
@test nthperm([0,1,2],3) == [1,0,2]
41+
@test_throws ArgumentError nthperm([0, 1, 2], 0)
42+
@test nthperm([0, 1, 2], 1) == [0, 1, 2]
43+
@test nthperm([0, 1, 2], 3) == [1, 0, 2]
44+
@test nthperm([0, 1, 2], 6) == [2, 1, 0]
45+
@test_throws ArgumentError nthperm([0, 1, 2], 7)
46+
47+
@test_throws ArgumentError nthperm([0:20;], big(0))
48+
@test nthperm([0:20;], big(1)) == [0:20;]
49+
@test nthperm([0:20;], factorial(big(20))) == [0; 20:-1:1]
50+
@test nthperm([0:20;], factorial(big(21))) == [20:-1:0;]
51+
@test_throws ArgumentError nthperm([0:20;], factorial(big(21)) + 1)
4252

4353
# Immutable AbstractArrays
4454
@test nthperm(1:5, 1) == [1,2,3,4,5]

0 commit comments

Comments
 (0)