質問

n個の要素があります。例として、7 要素、1234567 としましょう。7つあるのが分かりました!= これら 7 つの要素の組み合わせは 5040 通りあります。

次の 2 つの関数を含む高速アルゴリズムが必要です。

f(number) は、0 ~ 5039 の数値を一意の順列にマッピングします。

f'(permutation) は、順列を生成元の数値にマッピングします。

各順列に独自の一意の番号がある限り、数値と順列の対応関係は気にしません。

たとえば、次のような関数があるとします。

f(0) = '1234567'
f'('1234567') = 0

思いつく最速のアルゴリズムは、すべての順列を列挙し、両方向のルックアップ テーブルを作成することです。これにより、テーブルが作成されると、f(0) は O(1) になり、f('1234567') は文字列を検索します。ただし、これは特に n が大きくなるとメモリを大量に消費します。

誰かが、メモリの欠点なしに迅速に動作する別のアルゴリズムを提案できますか?

役に立ちましたか?

解決

n 個の要素の順列を記述するには、最初の要素が終了する位置には n 個の可能性があることがわかり、これを 0 から n-1 までの数値で記述することができます。次の要素が終了する位置については、n-1 個の可能性が残っているため、これを 0 から n-2 までの数値で記述することができます。
n 個の数字が得られるまで続けます。

n = 5 の例として、次のような順列を考えてみましょう。 abcdecaebd.

  • a, 最初の要素は 2 番目の位置になるため、それにインデックスを割り当てます。 1.
  • b 最終的には 4 番目の位置になり、インデックス 3 になりますが、残りの 3 番目なので、これを割り当てます。 2.
  • c 最初に残った位置で終了します。これは常に 0.
  • d 最後に残った位置に到達します。これは (残り 2 つの位置のうち) 1.
  • e 最終的には、インデックスが付けられた唯一の残りの位置になります。 0.

これでインデックスシーケンスが得られます {1, 2, 0, 1, 0}.

これで、たとえば 2 進数では、「xyz」は z + 2y + 4x を意味することが分かりました。10 進数の場合、
それはz + 10y + 100xです。各桁に何らかの重みが乗算され、結果が合計されます。重みの明白なパターンは、もちろん、重みが w = b^k であり、b は数値の基数、k は桁のインデックスです。(私は常に右から桁を数え、右端の桁のインデックス 0 から数えます。同様に、「最初の」桁について話すときは、一番右の桁を意味します。)

理由 数字の重みがこのパターンに従う理由は、0 から k までの数字で表現できる最大の数字が、数字 k+1 のみを使用して表現できる最小の数字よりも正確に 1 小さい必要があるためです。2 進数では、0111 は 1000 より 1 小さい値でなければなりません。10 進数の 099999 は 100000 より 1 小さい値でなければなりません。

変数ベースへのエンコーディング
後続の数字間の間隔が正確に 1 であることが重要なルールです。これを理解すると、インデックス シーケンスを次のように表すことができます。 変数の基数. 。各桁の底は、その桁のさまざまな可能性の量です。10 進数の場合、各桁には 10 の可能性があり、私たちのシステムでは、右端の桁には 1 つの可能性があり、左端には n つの可能性があります。ただし、右端の数字 (シーケンスの最後の数字) は常に 0 なので、省略します。つまり、2 から n までの塩基が残っています。一般に、k 番目の桁の基数は b[k] = k + 2 になります。数字 k に許可される最大値は、h[k] = b[k] - 1 = k + 1 です。

数字の重み w[k] に関するルールでは、h[i] * w[i] (i = 0 から i = k まで) の合計が 1 * w[k+1] に等しいことが必要です。繰り返し述べますと、w[k+1] = w[k] + h[k] * w[k] = w[k]*(h[k] + 1) となります。最初の重み w[0] は常に 1 である必要があります。そこから始まり、次の値が得られます。

k    h[k] w[k]    

0    1    1  
1    2    2    
2    3    6    
3    4    24   
...  ...  ...
n-1  n    n!  

(一般関係 w[k-1] = k!帰納法で簡単に証明できます。)

シーケンスを変換して得られる数値は、s[k] * w[k] の合計になります (k は 0 から n-1 までです)。ここで、s[k] はシーケンスの k 番目 (0 から始まる右端) の要素です。例として、前述のように右端の要素が取り除かれた {1, 2, 0, 1, 0} を考えてみましょう。 {1, 2, 0, 1}. 。合計は 1 * 1 + 0 * 2 + 2 * 6 + 1 * 24 = 37.

すべてのインデックスの最大位置を取得すると、{4, 3, 2, 1, 0} となり、これは 119 に変換されることに注意してください。数値エンコーディングの重みは数値をスキップしないように選択されているため、0 から 119 までのすべての数値が有効です。これらはちょうど 120 個あり、n!この例では n = 5 の場合、正確には異なる順列の数です。したがって、エンコードされた数値がすべての可能な順列を完全に指定していることがわかります。

変数ベースからのデコード
デコードは、2 進数または 10 進数への変換に似ています。一般的なアルゴリズムは次のとおりです。

int number = 42;
int base = 2;
int[] bits = new int[n];

for (int k = 0; k < bits.Length; k++)
{
    bits[k] = number % base;
    number = number / base;
}

変数の基数の場合:

int n = 5;
int number = 37;

int[] sequence = new int[n - 1];
int base = 2;

for (int k = 0; k < sequence.Length; k++)
{
    sequence[k] = number % base;
    number = number / base;

    base++; // b[k+1] = b[k] + 1
}

これにより、37 が正しくデコードされて {1, 2, 0, 1} に戻ります (sequence だろう {1, 0, 2, 1} このコード例では、何でも...適切にインデックスを付けている限り)。元のシーケンス {1, 2, 0, 1, 0} を戻すには、右端に 0 を追加するだけです (最後の要素の新しい位置の可能性は常に 1 つだけであることに注意してください)。

インデックスシーケンスを使用してリストを並べ替える
以下のアルゴリズムを使用して、特定のインデックス シーケンスに従ってリストを並べ替えることができます。残念ながら、これは O(n²) アルゴリズムです。

int n = 5;
int[] sequence = new int[] { 1, 2, 0, 1, 0 };
char[] list = new char[] { 'a', 'b', 'c', 'd', 'e' };
char[] permuted = new char[n];
bool[] set = new bool[n];

for (int i = 0; i < n; i++)
{
    int s = sequence[i];
    int remainingPosition = 0;
    int index;

    // Find the s'th position in the permuted list that has not been set yet.
    for (index = 0; index < n; index++)
    {
        if (!set[index])
        {
            if (remainingPosition == s)
                break;

            remainingPosition++;
        }
    }

    permuted[index] = list[i];
    set[index] = true;
}

順列の一般的な表現
通常、置換は、ここで行ったような直感的でない方法ではなく、単に置換が適用された後の各要素の絶対位置によって表されます。この例の {1, 2, 0, 1, 0} は abcdecaebd 通常は {1, 3, 0, 4, 2} で表されます。この表現では、0 から 4 (または一般に 0 から n-1) の各インデックスが 1 回だけ出現します。

この形式で順列を適用するのは簡単です。

int[] permutation = new int[] { 1, 3, 0, 4, 2 };

char[] list = new char[] { 'a', 'b', 'c', 'd', 'e' };
char[] permuted = new char[n];

for (int i = 0; i < n; i++)
{
    permuted[permutation[i]] = list[i];
}

それを反転すると、非常に似ています。

for (int i = 0; i < n; i++)
{
    list[i] = permuted[permutation[i]];
}

当社の表現から一般的な表現への変換
インデックス シーケンスを使用してリストを並べ替えるアルゴリズムを使用し、それを恒等順列 {0, 1, 2, ..., n-1} に適用すると、次の結果が得られることに注意してください。 逆数 順列。共通形式で表されます。({2, 0, 4, 1, 3} この例では)。

非反転の事前変異を取得するには、先ほど示した置換アルゴリズムを適用します。

int[] identity = new int[] { 0, 1, 2, 3, 4 };
int[] inverted = { 2, 0, 4, 1, 3 };
int[] normal = new int[n];

for (int i = 0; i < n; i++)
{
    normal[identity[i]] = list[i];
}

または、逆置換アルゴリズムを使用して、置換を直接適用することもできます。

char[] list = new char[] { 'a', 'b', 'c', 'd', 'e' };
char[] permuted = new char[n];

int[] inverted = { 2, 0, 4, 1, 3 };

for (int i = 0; i < n; i++)
{
    permuted[i] = list[inverted[i]];
}

一般的な形式で置換を処理するすべてのアルゴリズムは O(n) ですが、この形式での置換の適用は O(n²) であることに注意してください。順列を複数回適用する必要がある場合は、最初に順列を共通の表現に変換します。

他のヒント

私はO(n)のアルゴリズムを見つけた、ここでは簡単な説明<のhref = "http://antoinecomeau.blogspot.ca/2014/07/mapping-between-permutations-and.html" のrel =」はですnoreferrer nofollowを "> http://antoinecomeau.blogspot.ca/2014/07/mapping-between-permutations-and.html の

public static int[] perm(int n, int k)
{
    int i, ind, m=k;
    int[] permuted = new int[n];
    int[] elems = new int[n];

    for(i=0;i<n;i++) elems[i]=i;

    for(i=0;i<n;i++)
    {
            ind=m%(n-i);
            m=m/(n-i);
            permuted[i]=elems[ind];
            elems[ind]=elems[n-i-1];
    }

    return permuted;
}

public static int inv(int[] perm)
{
    int i, k=0, m=1;
    int n=perm.length;
    int[] pos = new int[n];
    int[] elems = new int[n];

    for(i=0;i<n;i++) {pos[i]=i; elems[i]=i;}

    for(i=0;i<n-1;i++)
    {
            k+=m*pos[perm[i]];
            m=m*(n-i);
            pos[elems[n-i-1]]=pos[perm[i]];
            elems[pos[perm[i]]]=elems[n-i-1];
    }

    return k;
}

の複雑さは、セクション10.1.1を参照して、n個の*ログ(N)までもたらすことができます fxtbookの(「レーマーコード(反転表)」、p.232ff)。    http://www.jjj.de/fxt/#fxtbookする セクション10.1.1.1速い方法(「大きなアレイと計算」p.235)に進んでください。 (GPLの、C ++)コード同じウェブページ上にある。

の各要素は、7つの位置のいずれかになります。一つの要素の位置を説明するために、次の3つのビットが必要になります。それはあなたが32ビットの値のすべての要素の位置を保存できることを意味します。この表現でもすべての要素が同じ位置にあることができるようになるので、それは、はるかに効率的であるからだが、私は、ビットマスキングが合理的に高速である必要があります信じています。

しかし、8つの以上の位置で、あなたはもっと何か気の利いが必要になります。

これは Jするにおける組み込み関数であることを起こります

   A. 1 2 3 4 5 6 7
0
   0 A. 1 2 3 4 5 6 7
1 2 3 4 5 6 7

   ?!7
5011
   5011 A. 1 2 3 4 5 6 7
7 6 4 5 1 3 2
   A. 7 6 4 5 1 3 2
5011

問題が解決しました。しかし、私はあなたがまだこれらの年後の溶液を必要とすることを確認していません。 LOL、私はちょうどので、このサイトに参加します... 私のJavaの順列クラスを確認してください。あなたは、インデックスを取得するシンボル順列を取得するには、インデックス上のベース、またはシンボルの順列を与えることができます。

ここに私の前変異種である

/**
 ****************************************************************************************************************
 * Copyright 2015 Fred Pang fred@pnode.com
 ****************************************************************************************************************
 * A complete list of Permutation base on an index.
 * Algorithm is invented and implemented by Fred Pang fred@pnode.com
 * Created by Fred Pang on 18/11/2015.
 ****************************************************************************************************************
 * LOL this is my first Java project. Therefore, my code is very much like C/C++. The coding itself is not
 * very professional. but...
 *
 * This Permutation Class can be use to generate a complete list of all different permutation of a set of symbols.
 * nPr will be n!/(n-r)!
 * the user can input       n = the number of items,
 *                          r = the number of slots for the items,
 *                          provided n >= r
 *                          and a string of single character symbols
 *
 * the program will generate all possible permutation for the condition.
 *
 * Say if n = 5, r = 3, and the string is "12345", it will generate sll 60 different permutation of the set
 * of 3 character strings.
 *
 * The algorithm I used is base on a bin slot.
 * Just like a human or simply myself to generate a permutation.
 *
 * if there are 5 symbols to chose from, I'll have 5 bin slot to indicate which symbol is taken.
 *
 * Note that, once the Permutation object is initialized, or after the constructor is called, the permutation
 * table and all entries are defined, including an index.
 *
 * eg. if pass in value is 5 chose 3, and say the symbol string is "12345"
 * then all permutation table is logically defined (not physically to save memory).
 * It will be a table as follows
 *  index  output
 *      0   123
 *      1   124
 *      2   125
 *      3   132
 *      4   134
 *      5   135
 *      6   143
 *      7   145
 *      :     :
 *      58  542
 *      59  543
 *
 * all you need to do is call the "String PermGetString(int iIndex)" or the "int[] PermGetIntArray(int iIndex)"
 * function or method with an increasing iIndex, starting from 0 to getiMaxIndex() - 1. It will return the string
 * or the integer array corresponding to the index.
 *
 * Also notice that in the input string is "12345" of  position 01234, and the output is always in accenting order
 * this is how the permutation is generated.
 *
 * ***************************************************************************************************************
 * ====  W a r n i n g  ====
 * ***************************************************************************************************************
 *
 * There is very limited error checking in this class
 *
 * Especially the  int PermGetIndex(int[] iInputArray)  method
 * if the input integer array contains invalid index, it WILL crash the system
 *
 * the other is the string of symbol pass in when the object is created, not sure what will happen if the
 * string is invalid.
 * ***************************************************************************************************************
 *
 */
public class Permutation
{
    private boolean bGoodToGo = false;      // object status
    private boolean bNoSymbol = true;
    private BinSlot slot;                   // a bin slot of size n (input)
    private int nTotal;                     // n number for permutation
    private int rChose;                     // r position to chose
    private String sSymbol;                 // character string for symbol of each choice
    private String sOutStr;
    private int iMaxIndex;                  // maximum index allowed in the Get index function
    private int[] iOutPosition;             // output array
    private int[] iDivisorArray;            // array to do calculation

    public Permutation(int inCount, int irCount, String symbol)
    {
        if (inCount >= irCount)
        {
            // save all input values passed in
            this.nTotal = inCount;
            this.rChose = irCount;
            this.sSymbol = symbol;

            // some error checking
            if (inCount < irCount || irCount <= 0)
                return;                                 // do nothing will not set the bGoodToGo flag

            if (this.sSymbol.length() >= inCount)
            {
                bNoSymbol = false;
            }

            // allocate output storage
            this.iOutPosition = new int[this.rChose];

            // initialize the bin slot with the right size
            this.slot = new BinSlot(this.nTotal);

            // allocate and initialize divid array
            this.iDivisorArray = new int[this.rChose];

            // calculate default values base on n & r
            this.iMaxIndex = CalPremFormula(this.nTotal, this.rChose);

            int i;
            int j = this.nTotal - 1;
            int k = this.rChose - 1;

            for (i = 0; i < this.rChose; i++)
            {
                this.iDivisorArray[i] = CalPremFormula(j--, k--);
            }
            bGoodToGo = true;       // we are ready to go
        }
    }

    public String PermGetString(int iIndex)
    {
        if (!this.bGoodToGo) return "Error: Object not initialized Correctly";
        if (this.bNoSymbol) return "Error: Invalid symbol string";
        if (!this.PermEvaluate(iIndex)) return "Invalid Index";

        sOutStr = "";
        // convert string back to String output
        for (int i = 0; i < this.rChose; i++)
        {
            String sTempStr = this.sSymbol.substring(this.iOutPosition[i], iOutPosition[i] + 1);
            this.sOutStr = this.sOutStr.concat(sTempStr);
        }
        return this.sOutStr;
    }

    public int[] PermGetIntArray(int iIndex)
    {
        if (!this.bGoodToGo) return null;
        if (!this.PermEvaluate(iIndex)) return null ;
        return this.iOutPosition;
    }

    // given an int array, and get the index back.
    //
    //  ====== W A R N I N G ======
    //
    // there is no error check in the array that pass in
    // if any invalid value in the input array, it can cause system crash or other unexpected result
    //
    // function pass in an int array generated by the PermGetIntArray() method
    // then return the index value.
    //
    // this is the reverse of the PermGetIntArray()
    //
    public int PermGetIndex(int[] iInputArray)
    {
        if (!this.bGoodToGo) return -1;
        return PermDoReverse(iInputArray);
    }


    public int getiMaxIndex() {
    return iMaxIndex;
}

    // function to evaluate nPr = n!/(n-r)!
    public int CalPremFormula(int n, int r)
    {
        int j = n;
        int k = 1;
        for (int i = 0; i < r; i++, j--)
        {
            k *= j;
        }
        return k;
    }


//  PermEvaluate function (method) base on an index input, evaluate the correspond permuted symbol location
//  then output it to the iOutPosition array.
//
//  In the iOutPosition[], each array element corresponding to the symbol location in the input string symbol.
//  from location 0 to length of string - 1.

    private boolean PermEvaluate(int iIndex)
    {
        int iCurrentIndex;
        int iCurrentRemainder;
        int iCurrentValue = iIndex;
        int iCurrentOutSlot;
        int iLoopCount;

        if (iIndex >= iMaxIndex)
            return false;

        this.slot.binReset();               // clear bin content
        iLoopCount = 0;
        do {
            // evaluate the table position
            iCurrentIndex = iCurrentValue / this.iDivisorArray[iLoopCount];
            iCurrentRemainder = iCurrentValue % this.iDivisorArray[iLoopCount];

            iCurrentOutSlot = this.slot.FindFreeBin(iCurrentIndex);     // find an available slot
            if (iCurrentOutSlot >= 0)
                this.iOutPosition[iLoopCount] = iCurrentOutSlot;
            else return false;                                          // fail to find a slot, quit now

            this.slot.setStatus(iCurrentOutSlot);                       // set the slot to be taken
            iCurrentValue = iCurrentRemainder;                          // set new value for current value.
            iLoopCount++;                                               // increase counter
        } while (iLoopCount < this.rChose);

        // the output is ready in iOutPosition[]
        return true;
    }

    //
    // this function is doing the reverse of the permutation
    // the input is a permutation and will find the correspond index value for that entry
    // which is doing the opposit of the PermEvaluate() method
    //
    private int PermDoReverse(int[] iInputArray)
    {
        int iReturnValue = 0;
        int iLoopIndex;
        int iCurrentValue;
        int iBinLocation;

        this.slot.binReset();               // clear bin content

        for (iLoopIndex = 0; iLoopIndex < this.rChose; iLoopIndex++)
        {
            iCurrentValue = iInputArray[iLoopIndex];
            iBinLocation = this.slot.BinCountFree(iCurrentValue);
            this.slot.setStatus(iCurrentValue);                          // set the slot to be taken
            iReturnValue = iReturnValue + iBinLocation * this.iDivisorArray[iLoopIndex];
        }
        return iReturnValue;
    }


    /*******************************************************************************************************************
     *******************************************************************************************************************
     * Created by Fred on 18/11/2015.   fred@pnode.com
     *
     * *****************************************************************************************************************
     */
    private static class BinSlot
    {
        private int iBinSize;       // size of array
        private short[] eStatus;    // the status array must have length iBinSize

        private BinSlot(int iBinSize)
        {
            this.iBinSize = iBinSize;               // save bin size
            this.eStatus = new short[iBinSize];     // llocate status array
        }

        // reset the bin content. no symbol is in use
        private void binReset()
        {
            // reset the bin's content
            for (int i = 0; i < this.iBinSize; i++) this.eStatus[i] = 0;
        }

        // set the bin position as taken or the number is already used, cannot be use again.
        private void  setStatus(int iIndex) { this.eStatus[iIndex]= 1; }

        //
        // to search for the iIndex th unused symbol
        // this is important to search through the iindex th symbol
        // because this is how the table is setup. (or the remainder means)
        // note: iIndex is the remainder of the calculation
        //
        // for example:
        // in a 5 choose 3 permutation symbols "12345",
        // the index 7 item (count starting from 0) element is "1 4 3"
        // then comes the index 8, 8/12 result 0 -> 0th symbol in symbol string = '1'
        // remainder 8. then 8/3 = 2, now we need to scan the Bin and skip 2 unused bins
        //              current the bin looks 0 1 2 3 4
        //                                    x o o o o     x -> in use; o -> free only 0 is being used
        //                                      s s ^       skipped 2 bins (bin 1 and 2), we get to bin 3
        //                                                  and bin 3 is the bin needed. Thus symbol "4" is pick
        // in 8/3, there is a remainder 2 comes in this function as 2/1 = 2, now we have to pick the empty slot
        // for the new 2.
        // the bin now looks 0 1 2 3 4
        //                   x 0 0 x 0      as bin 3 was used by the last value
        //                     s s   ^      we skip 2 free bins and the next free bin is bin 4
        //                                  therefor the symbol "5" at the symbol array is pick.
        //
        // Thus, for index 8  "1 4 5" is the symbols.
        //
        //
        private int FindFreeBin(int iIndex)
        {
            int j = iIndex;

            if (j < 0 || j > this.iBinSize) return -1;               // invalid index

            for (int i = 0; i < this.iBinSize; i++)
            {
                if (this.eStatus[i] == 0)       // is it used
                {
                    // found an empty slot
                    if (j == 0)                 // this is a free one we want?
                        return i;               // yes, found and return it.
                    else                        // we have to skip this one
                        j--;                    // else, keep looking and count the skipped one
                }
            }
            assert(true);           // something is wrong
            return -1;              // fail to find the bin we wanted
        }

        //
        // this function is to help the PermDoReverse() to find out what is the corresponding
        // value during should be added to the index value.
        //
        // it is doing the opposite of int FindFreeBin(int iIndex) method. You need to know how this
        // FindFreeBin() works before looking into this function.
        //
        private int BinCountFree(int iIndex)
        {
            int iRetVal = 0;
            for (int i = iIndex; i > 0; i--)
            {
                if (this.eStatus[i-1] == 0)       // it is free
                {
                    iRetVal++;
                }
            }
            return iRetVal;
        }
    }
}
// End of file - Permutation.java

、ここでは、クラスの使用方法を示すために私のメインクラスです。

/*
 * copyright 2015 Fred Pang
 *
 * This is the main test program for testing the Permutation Class I created.
 * It can be use to demonstrate how to use the Permutation Class and its methods to generate a complete
 * list of a permutation. It also support function to get back the index value as pass in a permutation.
 *
 * As you can see my Java is not very good. :)
 * This is my 1st Java project I created. As I am a C/C++ programmer for years.
 *
 * I still have problem with the Scanner class and the System class.
 * Note that there is only very limited error checking
 *
 *
 */

import java.util.Scanner;

public class Main
{
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args)
    {
        Permutation perm;       // declear the object
        String sOutString = "";
        int nCount;
        int rCount;
        int iMaxIndex;

        // Get user input
        System.out.println("Enter n: ");
        nCount = scanner.nextInt();

        System.out.println("Enter r: ");
        rCount = scanner.nextInt();

        System.out.println("Enter Symbol: ");
        sOutString = scanner.next();

        if (sOutString.length() < rCount)
        {
            System.out.println("String too short, default to numbers");
            sOutString = "";
        }

        // create object with user requirement
        perm = new Permutation(nCount, rCount, sOutString);

        // and print the maximum count
        iMaxIndex = perm.getiMaxIndex();
        System.out.println("Max count is:" + iMaxIndex);

        if (!sOutString.isEmpty())
        {
            for (int i = 0; i < iMaxIndex; i++)
            {   // print out the return permutation symbol string
                System.out.println(i + " " + perm.PermGetString(i));
            }
        }
        else
        {
            for (int i = 0; i < iMaxIndex; i++)
            {
                System.out.print(i + " ->");

                // Get the permutation array
                int[] iTemp = perm.PermGetIntArray(i);

                // print out the permutation
                for (int j = 0; j < rCount; j++)
                {
                    System.out.print(' ');
                    System.out.print(iTemp[j]);
                }

                // to verify my PermGetIndex() works. :)
                if (perm.PermGetIndex(iTemp)== i)
                {
                    System.out.println(" .");
                }
                else
                {   // oops something is wrong :(
                    System.out.println(" ***************** F A I L E D *************************");
                    assert(true);
                    break;
                }
            }
        }
    }
}
//
// End of file - Main.java

の楽しみを持っています。 :)

あなたは、再帰的なアルゴリズムを使用して順列をエンコードすることができます。 N - 置換(番号の一部順序{0、...、N-1})の形である場合、{X、...}次に、X + N *(N-1)の符号化として符号化します"..." 番号{0、N-1}で表される-permutation - {X}。一口のような音、ここでいくつかのコードは次のとおりです。

// perm[0]..perm[n-1] must contain the numbers in {0,..,n-1} in any order.
int permToNumber(int *perm, int n) {
  // base case
  if (n == 1) return 0;

  // fix up perm[1]..perm[n-1] to be a permutation on {0,..,n-2}.
  for (int i = 1; i < n; i++) {
    if (perm[i] > perm[0]) perm[i]--;
  }

  // recursively compute
  return perm[0] + n * permToNumber(perm + 1, n - 1);
}

// number must be >=0, < n!
void numberToPerm(int number, int *perm, int n) {
  if (n == 1) {
    perm[0] = 0;
    return;
  }
  perm[0] = number % n;
  numberToPerm(number / n, perm + 1, n - 1);

  // fix up perm[1] .. perm[n-1]
  for (int i = 1; i < n; i++) {
    if (perm[i] >= perm[0]) perm[i]++;
  }
}

このアルゴリズムは、O(N ^ 2)です。誰もがO(n)のアルゴリズムを持っている場合。ボーナスポイント

どのような興味深い質問!

あなたのすべての要素が数値である場合は、

、あなたは実際の数値に文字列からそれらを変換を検討する必要があります。そして、あなたは順序でそれらを置くことによって順列の全てをソートし、そして配列にそれらを配置することができるでしょう。その後、あなたはそこに様々な検索アルゴリズムのいずれかにオープンになります。

私は私の前の回答(削除)に性急だった、私はしかし、実際の答えを持っています。これは、(私の答え関連 factoradic に、同様の概念によって提供され、順列に関連しています組み合わせに、私は)その混乱をお詫び申し上げます。私は、Wikipediaのリンクを投稿する嫌いが、私はしばらく前にやったいくつかの理由で理解不能ですWRITEUP。要求されたのであれば、私はこの後に展開することができます。

これについて書かれた本があります。申し訳ありませんが、私はそれの名前を(あなたはウィキペディアからかなりおそらくそれを見つけるでしょう)覚えていません。 とにかく、私はその列挙システムのPython実装を書いた: http://kks.cabal.fi/Kombinaattori それのいくつかはフィンランド語であるが、単にコードと名前の変数をコピー...

の関連する問題は、逆順列のみ順列配列が知られている元の順序に並べ替えたベクトルを回復する順列を計算します。ここで(PHPで)O(n)のコードである

// Compute the inverse of a permutation
function GetInvPerm($Perm)
    {
    $n=count($Perm);
    $InvPerm=[];
    for ($i=0; $i<$n; ++$i)
        $InvPerm[$Perm[$i]]=$i;
    return $InvPerm;
    } // GetInvPerm

デビッド・スペクター 春のソフトウェア

私はこの正確な質問を持っていたし、私はPythonのソリューションを提供するだろうと思いました。これは、O(N ^ 2)です。

import copy

def permute(string, num):
    ''' generates a permutation '''
    def build_s(factoradic): # Build string from factoradic in list form
        string0 = copy.copy(string)
        n = []
        for i in range(len(factoradic)):
            n.append(string0[factoradic[i]])
            del string0[factoradic[i]]
        return n

    f = len(string)
    factoradic = []
    while(f != 0): # Generate factoradic number list
        factoradic.append(num % f)
        num = (num - factoradic[-1])//f
        f -= 1

    return build_s(factoradic)

s = set()
# Print 120 permutations of this string
for i in range(120):
    m = permute(list('abcde'), i)
    s.add(''.join(m))

print(len(s)) # Check that we have 120 unique permutations

これは非常に単純です。数のfactoradic表現を生成した後、私は単なる文字列から文字を選択し、削除します。これはO(N ^ 2)溶液である理由文字列から削除することである。

アントワーヌのソリューションは、パフォーマンスのために優れてます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top