#if !defined  HAVE_MSET_PERM_GRAY_H__
#define       HAVE_MSET_PERM_GRAY_H__
// This file is part of the FXT library.
// Copyright (C) 2010, 2012, 2014, 2019, 2023 Joerg Arndt
// License: GNU General Public License version 3 or later,
// see the file COPYING.txt in the main directory.


#include "comb/comb-print.h"
#include "fxtio.h"

#include "fxttypes.h"
#include "aux0/swap.h"


class mset_perm_gray
// Multiset permutations in minimal-change order (Fred Lunnon's Gray code).
//.
// Adaptation of Java code by Fred Lunnon.
// Original documentation at end of file.
{
private:
    ulong *R;   // permuted elements
    ulong *P;   // permutation
    ulong *Q;   // inverse permutation
    ulong *D;   // direction, "drift"
    ulong k;    // number of different sorts of objects
    ulong n;    // number of objects
    ulong sw1, sw2;  // positions swapped with last update
    ulong *E;   // number of elements '1' in r[0], '2' in r[1], ..., 'k' in r[k-1]

    mset_perm_gray(const mset_perm_gray&) = delete;
    mset_perm_gray & operator = (const mset_perm_gray&) = delete;

public:
    explicit mset_perm_gray(const ulong *tr, ulong tk)
    {
        k = tk;
        E = new ulong[k];
        for (ulong j=0; j<k; ++j)  E[j] = tr[j];
        n = 0;
        for (ulong j=0; j<k; ++j)  n += E[j];

        // Sentinels at indices 0, n+1, n+2, n+3:
        R = new ulong[n+4];
        P = new ulong[n+4];
        Q = new ulong[n+4];
        D = new ulong[n+4];

        first();
    }

    ~mset_perm_gray()
    {
        delete [] E;
        delete [] R;
        delete [] P;
        delete [] Q;
        delete [] D;
    }

    const ulong * data_mset_perm()  const  { return R + 1; }
    const ulong * data_perm()  const  { return P + 1; }
    const ulong * data_inv_perm()  const  { return Q + 1; }
    void get_swaps(ulong &tsw1, ulong &tsw2)  const  { tsw1 = sw1;  tsw2 = sw2; }
    ulong get_n()  const  { return n; }

    void first()
    {
        sw1 = sw2 = 0;

        for (ulong j=0, i=1;  j < k;  ++j)
            for (ulong h = E[j];  h != 0;  --h, ++i)  R[i] = j + 1;

        for (ulong j=1;  j <= n;  ++j)  { P[j] = j;  Q[j] = j;  D[j] = +1UL; }

        // sentinels:
        R[0] = 0;  P[0] = 0;  Q[0] = 0;  D[0] = 0;
        ulong j;
        j = n+1;  R[j] = 0;    P[j] = 0;    Q[j] = n+2;  D[j] = 0;
        j = n+2;  R[j] = k+1;  P[j] = n+1;  Q[j] = n+3;  D[j] = +1;
        j = n+3;  R[j] = k+2;  P[j] = n+2;  Q[j] = 0;    D[j] = +1;
    }

    bool next()
    {
        // locate earliest unblocked element at j, starting at blocked element 0
        ulong j = 0, i = 0, d = 0, l = 0;  // init of l not needed
        while ( R[j] >= R[i] )
        {
            D[j] = -d;  // blocked at j; reverse drift d pre-emptively

            // next element at j, neighbor at i:
            j = Q[ P[j] + 1 ];
            d = D[j];
            i = j+d;

            if ( R[j-1] != R[j] )  l = j;  // save left end of run in l
            else
            {
                if ( (long)d < 0)  i = l - 1;
            }
        }

        if ( j > n )  return false;  // current permutation is last

        // restore left end at head of run
        // shift run of equal rank from i-d,i-2d,...,l to i,i-d,...,l+d
        if ( (long)d < 0 )  l = j;
        ulong e = D[i],  p = P[i];  // save neighbor drift e and identifier p

        for (ulong w=i;  w != l;  w-=d)
        {
            P[w] = P[w-d];
            Q[ P[w] ] = w;
            D[w] = -1UL;  // reset drifts of run tail elements
        }

        sw1 = i - 1;  sw2 = l - 1;  // save positions swapped
        swap2( R[i], R[l] );

        D[l] = e;  D[i] = d;  // restore drifts of head and neighbor
        P[l] = p;  Q[p] = l;  // wrap neighbor around to other end

        return  true;
    }

    void print(const char *bla)  const
    // Print multiset permutation
    { ::print_perm(bla, data_mset_perm(), n, false); }

    void print_perm(const char *bla)  const
    // Print underlying permutation
    { ::print_perm(bla, data_perm(), n, false); }

    void print_inv_perm(const char *bla)  const
    // Print inverse of underlying permutation
    { ::print_perm(bla, data_inv_perm(), n, false); }

    void print_dirs(const char *bla)  const
    // Print D[]
    {
        if ( bla )  cout << bla;
        cout << "[";
        for (ulong j=0; j < n+2; ++j)
        {
            ulong d = D[j];
            cout << " ";
            if ( (long)d < 0 )  cout << '-';
            if ( (long)d > 0 )  cout << '+';
            if ( d==0 )  cout << '.';
        }
        cout << " ]";
    }
};
// -------------------------

/*
Original documentation by Fred Lunnon:

 Generate bag-permutations of m elements, ordered by nearly adjacent
 transposition; generator value = m+1 on termination; assumes 0
 <= n <= m, m > 0; 4 sentinels; no pre-initialisation.

 A "run" is defined to be a sequence of equally ranked elements in
 consecutive locations (and with consecutive identifiers), such that all
 but the righthand end (highest location) are drifting right (d = +1).
 The drift of the righthand element at j determines that of the entire run.
 A run is "blocked" when the element adjacent in its direction of drift at i
 has equal or lower rank. The element adjacent to a run at its lefthand end
 is of different rank; at its righthand end may be another of equal rank.
 Generator employs Steinhaus-Johnson-Trotter adjacent transposition strategy
 to exchange the earliest (by identifier) unblocked run at j with the single
 element at i. Individual elements within a run behave as though under the
 action of a combination generator by nearly-adjacent transpositions;
 all permutations of the user bag of ranks are transpositions, most of
 which are actually adjacent.
 Once an unblocked element is found, the attached run is shifted one place
 along direction d, the end elements transposed, and all but the rightmost
 drift set leftwards; the drift of all earlier elements is reversed.
 In order to avoid unnecesary and nested loops, reversal takes place during
 search, and the left end of a run is retained in l for future reference.
 Spatial blocking sentinels ranked lowest are installed at either end, and
 temporal termination sentinels ranked highest placed off the righthand end.

 Each element has unique identifier p, lower p drifting more frequently;
 R[k] = rank (positive integer user symbol) of element at k;
 P[k] = identifier p of element at k, 0 <= p < m+3;
 Q[p] = location k of element p, 0 <= k < m+3;
 D[k] = current drift direction d of element at k, -1 <= d <= +1.
 i,j,k,l locate elements in current permutation;
 d,e = direction of element at j,i; l holds left end of current run.
 Arrays are extended by sentinels indexed 0 at left, m+1,m+2,m+3 at right;
 all subscripts run from 0 to array.length;
*/


#endif  // !defined HAVE_MSET_PERM_GRAY_H__
