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

#include "perm/printcycles.h"  // print_cycles_ce()
#include "comb/comb-print.h"  // print_vec()
#include "bits/bitlow.h"  // lowest_one_idx()

#include "fxttypes.h"
#include "jjassert.h"

// code and algorithm generated with AI (Claude Opus 5.5)


// The lowest set bit in next() is found with __builtin_ctzl() if
// HAVE_GCC_BUILTINS is defined, else with lowest_one_idx() of FXT
// (bits/bitlow.h).  With -march=native on x86-64 the builtin gives the
// tzcnt instruction, lowest_one_idx() the bsf instruction (inline asm).
// HAVE_GCC_BUILTINS is not a predefined macro, it is defined here if the
// compiler has __builtin_ctzl(), as tested with __has_builtin()
// (g++ >= 10, clang++); compile with -DNO_GCC_BUILTINS to disable.
// The two #if lines must stay separate: a compiler without
// __has_builtin() could not parse the second test.
#if defined __has_builtin && !defined NO_GCC_BUILTINS && !defined HAVE_GCC_BUILTINS
#if __has_builtin(__builtin_ctzl)
#define HAVE_GCC_BUILTINS
#endif
#endif


class perm_genus0_both
// Permutations of genus 0 of n elements (n <= 63), both in
// cycle form (C[], E[]) and in array form P[].
// There are Catalan(n) such permutations (OEIS sequence A000108).
// Limit n <= 63 (checked in the constructor): as in perm_genus0_cycles,
// the set of used elements, plus the sentinel element n, is a bit mask
// in one word.
// The limit is no restriction for generating all objects: there are
// Catalan(n) of them, at about 200 million per second this takes
// 32 seconds for n=20, 6.5 hours for n=25, 7 months for n=30, and
// 400000 years for n=40.  It only matters when generating a part of the
// objects for larger n.
// Same algorithm and order as class perm_genus0_cycles (see there),
// additionally the array form is updated, which costs O(1) per changed
// position of the cycle form.
// For each position t of the cycle form we keep the start (=minimum)
// of the cycle containing C[t] in S[t], needed for P[last] = start.
//
// Algorithm B (Permutations of genus 0, cycle form and array form).
// Algorithm C of class perm_genus0_cycles (see there), with two more
// arrays: S[t] = start (minimum) of the cycle containing C[t], and the
// array form P.  Changes to the steps of Algorithm C:
//   C1. Also set S[t] <- t, P[t] <- t for 0 <= t < n.
//   C6. Also set P[C[t]] <- c, S[t+1] <- S[t], P[c] <- S[t].
//       (C[t] is followed by c in its cycle, c closes the cycle.)
//   C7. Also set S[s] <- x, P[x] <- x for each new fixed point x.
// Each changed position of the cycle form costs O(1) for the array
// form, so the cost per object is within a constant factor of that of
// Algorithm C given in file perm-genus0-cycles.h.
{
private:
    ulong n;     // Number of elements, permutation of {0, 1, ..., n-1}
    ulong *C;    // concatenated cycles
    ulong *E;    // E[t] != 0 iff C[t] is last element of its cycle
    ulong *S;    // S[t] = first element of cycle containing C[t]
    ulong *P;    // array form
    ulong all;   // bit mask with bits 0, 1, ..., n-1 set (elements)

    perm_genus0_both(const perm_genus0_both&) = delete;
    perm_genus0_both & operator = (const perm_genus0_both&) = delete;
public:
    explicit perm_genus0_both(ulong tn)
    {
        n = tn;
        jjassert( n <= 63 );  // need one extra (sentinel) bit in a word
        C = new ulong[n+1];  // one extra element (never used) for n==0
        E = new ulong[n+1];
        S = new ulong[n+1];
        P = new ulong[n+1];
        all = (1UL << n) - 1;
        first();
    }

    ~perm_genus0_both()
    {
        delete [] C;
        delete [] E;
        delete [] S;
        delete [] P;
    }

    const ulong* data()  const  { return P; }   // array form
    const ulong* cyc()   const  { return C; }   // elements in cycle order
    const ulong* ends()  const  { return E; }   // end-of-cycle flags
    ulong size()  const  { return n; }

    void first()
    // Identity permutation: (0) (1) ... (n-1).
    {
        for (ulong t=0; t<n; ++t)  { C[t] = t;  E[t] = 1;  S[t] = t;  P[t] = t; }
    }

    bool next()
    // Generate next permutation in token-lex order of the cycle form.
    // Return false if current was the last.
    {
        if ( n <= 1 )  return false;

        // Scan back (see perm_genus0_cycles::next()):
        ulong used = all | (1UL << n);  // with sentinel bit n
        ulong t = n - 1;
        ulong c;
        while ( true )
        {
            used ^= 1UL << C[t];
            --t;
            c = 1 + ( E[t] ? C[t] : C[t+1] );
            if ( 0 == (used & (1UL << c)) )  break;
            if ( t == 0 )  return false;  // current is last
        }

        // C[t] continues with c, which closes the cycle:
        const ulong st = S[t];
        E[t] = 0;
        P[ C[t] ] = c;
        C[t+1] = c;  E[t+1] = 1;  S[t+1] = st;
        P[c] = st;
        used |= 1UL << c;

        // Remaining elements in increasing order as fixed points:
        ulong f = all & ~used;
        ulong s = t + 2;
        while ( f )
        {
#if defined HAVE_GCC_BUILTINS
            const ulong x = (ulong)__builtin_ctzl(f);  // f != 0
#else
            const ulong x = lowest_one_idx(f);
#endif
            C[s] = x;  E[s] = 1;  S[s] = x;
            P[x] = x;
            ++s;
            f &= f - 1;  // remove lowest bit
        }

        return true;
    }

    void print(const char *bla, bool dfz=false)  const
    // Print array form.
    { print_vec(bla, data(), n, dfz); }

    void print_cycles(const char *bla)  const
    // Print cycle form.
    // These are also non-crossing set partitions.
    { print_cycles_ce(bla, C, E, n); }

    bool OK()  const
    // Check that the array form agrees with the cycle form.
    {
        ulong t = 0;
        while ( t < n )
        {
            const ulong st = C[t];
            if ( S[t] != st )  return false;
            while ( !E[t] )
            {
                if ( S[t+1] != st )  return false;
                if ( P[C[t]] != C[t+1] )  return false;
                ++t;
            }
            if ( P[C[t]] != st )  return false;
            ++t;
        }
        return true;
    }
};
// -------------------------


#endif  // !defined HAVE_PERM_GENUS0_BOTH_H__
