
#include "fxttypes.h"
#include "perm/permq.h"
#include "ds/bitarray.h"

#include "fxtio.h"

ulong
print_cycles(const ulong *f, ulong n, bitarray *bp/*=0*/)
// Print the cycles of the permutation.
// Return number of fixed points.
{
    bitarray *tp = bp;
    if ( 0==bp )  tp = new bitarray(n);  // tags
    tp->clear_all();

    ulong ct = 0;  // # of fixed points
    for (ulong k=0; k<n; ++k)
    {
        if ( tp->test_clear(k) )  continue;  // already processed
        tp->set(k);

        // follow a cycle:
        ulong i = k;
        ulong g = f[i];  // next index
        if ( g==i )  // fixed point ?
        {
            ++ct;
            continue;
        }

        cout << " ( " << i;
        while ( 0==(tp->test_set(g)) )
        {
//            cout << " <-- " << setw(3) << g;
            cout << ", " << g;
            g = f[g];
        }
        cout << " )";
    }

    if ( 0==bp )  delete tp;

    return  ct;
}
// -------------------------

ulong
print_cycle(const ulong *f, ulong e0/*=0*/)
// Print the cycle that contains e0.
// Return length of the cycle.
{
    ulong e = e0;
    ulong ct = 0;
    cout << "( ";
    do  { ++ct; cout << e << ", "; e=f[e]; }  while ( e!=e0 );
    cout << ")";
    return ct;
}
// -------------------------

