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

#include "fxttypes.h"


class dyck_rgs
// Restricted growth strings (RGS) corresponding to k-ary Dyck words (k=i+1):
//  s[0,...,n-1] such that s[k] <= s[k-1]+i
// Lexicographic order.
// Number of RGS is binomial(i*n,n)/((i-1)*n+1), (Catalan numbers for i=1).
{
public:
    ulong *s_;  // restricted growth string
    ulong n_;   // Length of strings
    ulong i_;   // s[k] <= s[k-1]+i
    // i==1 ==> RGS for strings fo valid paren pairings

public:
    dyck_rgs(ulong n, ulong i=1)
    {
        n_ = n;
        s_ = new ulong[n_];
        i_ = i;
        first();
    }

    ~dyck_rgs()
    {
        delete [] s_;
    }

    void first()
    {
        ulong n = n_;
        for (ulong k=0; k<n; ++k)  s_[k] = 0;
    }

    ulong next()
    // Return index of first changed element in s[],
    // Return zero if current string is the last
    {
        ulong k = n_;

    start:
        --k;
        if ( k==0 )  return 0;

        ulong sk = s_[k] + 1;
        ulong mp = s_[k-1] + i_;
        if ( sk > mp )  // "carry"
        {
            s_[k] = 0;
            goto start;
        }

        s_[k] = sk;
        return k;
    }

    const ulong* data()  const  { return s_; }

    void print()  const;
};
// -------------------------


#endif  // !defined HAVE_DYCK_RGS_H__
