From 3376d7c0b46e4b035004c71e631d660f0ee9bbf9 Mon Sep 17 00:00:00 2001 From: Stefan Karpinski Date: Sat, 4 Aug 2012 01:03:17 -0400 Subject: [PATCH] invperm: don't rely on OOB errors for behavior; isperm: faster alg. closes #1113. --- base/combinatorics.jl | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/base/combinatorics.jl b/base/combinatorics.jl index 569672dbff9e8..f34f4883a6c95 100644 --- a/base/combinatorics.jl +++ b/base/combinatorics.jl @@ -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