Skip to content

Commit 54bd3ee

Browse files
author
lmshk
committed
Improve nthperm! argument checking.
1 parent 3c08c9a commit 54bd3ee

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
@@ -133,15 +133,15 @@ done(p::MultiSetPermutations, s) =
133133

134134
"In-place version of nthperm."
135135
function nthperm!(a::AbstractVector, k::Integer)
136-
k -= 1 # make k 1-indexed
137-
k < 0 && throw(ArgumentError("permutation k must be ≥ 0, got $k"))
138136
n = length(a)
139137
n == 0 && return a
140-
f = factorial(oftype(k, n-1))
138+
f = factorial(oftype(k, n))
139+
0 < k <= f || throw(ArgumentError("permutation k must satisfy 0 < k ≤ $f, got $k"))
140+
k -= 1 # make k 1-indexed
141141
for i=1:n-1
142+
f = div(f, n - i + 1)
142143
j = div(k, f) + 1
143144
k = k % f
144-
f = div(f, n-i)
145145

146146
j = j+i-1
147147
elt = a[j]

test/permutations.jl

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

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

4454
@test_throws ArgumentError parity([0])
4555
@test_throws ArgumentError parity([1,2,3,3])

0 commit comments

Comments
 (0)