Skip to content

Commit

Permalink
invperm: don't rely on OOB errors for behavior; isperm: faster alg.
Browse files Browse the repository at this point in the history
closes #1113.
  • Loading branch information
StefanKarpinski committed Aug 4, 2012
1 parent 1a81306 commit 3376d7c
Showing 1 changed file with 16 additions and 12 deletions.
28 changes: 16 additions & 12 deletions base/combinatorics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -116,25 +116,29 @@ function nthperm!(a::AbstractVector, k::Integer)
end
nthperm(a::AbstractVector, k::Integer) = nthperm!(copy(a),k)

# todo: should be O(n)
isperm(a::AbstractVector) = isequal([1:length(a)], sort(a))

# inverse permutation
# invert a permutation
function invperm(a::AbstractVector)
b = zero(a) # similar vector of zeros
try
for i = 1:length(a)
if b[a[i]] != 0 error() end
b[a[i]] = i
n = length(a)
for i = 1:n
j = a[i]
if !(1 <= j <= n) || b[j] != 0
error("invperm: input is not a permutation")
end
catch
# TODO: should catch more selectively, but at
# the moment, this is just an ExceptionError.
error("invperm: input must be a permutation")
b[j] = i
end
return b
end

function isperm(a::AbstractVector)
try
invperm(a)
true
catch
false
end
end

# Algorithm T from TAoCP 7.2.1.3
function combinations(a::AbstractVector, t::Integer)
# T1
Expand Down

0 comments on commit 3376d7c

Please sign in to comment.