Click here to Skip to main content
15,883,809 members
Articles / Programming Languages / C#

Non-recursive Permutations and Combinations

Rate me:
Please Sign up or sign in to vote.
4.87/5 (11 votes)
22 Dec 2010CPOL4 min read 47.7K   365   16  
Enumerating permutations and combinations without recursion.

# region Heading

/**************************************************************************************************************/
/*                                                                                                            */
/*  LibExt.Permutations.cs                                                                                    */
/*                                                                                                            */
/*  Calculates the Permutations of the provided Things                                                        */
/*                                                                                                            */
/*  This is free code, use it as you require. If you modify it please use your own namespace.                 */
/*                                                                                                            */
/*  If you like it or have suggestions for improvements please let me know at: PIEBALDconsult@aol.com         */
/*                                                                                                            */
/*  Modification history:                                                                                     */
/*  2009-07-20          Sir John E. Boucher     Created                                                       */
/*                                                                                                            */
/**************************************************************************************************************/

# endregion

namespace PIEBALD.Lib.LibExt.Permutations
{
    using PIEBALD.Lib.LibExt.ApplyIndices ;

    public static class LibExt
    {
        /**
        <summary>
            Calculates the Permutations of the provided Things.
        </summary>
        <param name="Things">
            An IList of items for which you want Permutations.
        </param>
        <param name="Take">
            The number of Things to include in each Permutation.
        </param>
        <returns>
            An enumerator of the Permutations.
        </returns>
        <exception cref="System.ArgumentNullException">
            If Things is null.
        </exception>
        <exception cref="System.ArgumentNullException">
            If Take is less than one (1) or greater than the number of Things.
        </exception>
        */
        public static System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<T>>
        Permutations<T>
        (
            this System.Collections.Generic.IList<T> Things
        ,
            int                                      Take
        )
        {
            if ( Things == null )
            {
                throw ( new System.ArgumentNullException
                (
                    "Things"
                ,
                    "Things must not be null"
                ) ) ;
            }
        
            if ( Take < 1 )
            {
                throw ( new System.ArgumentOutOfRangeException 
                ( 
                    "Take" 
                , 
                    Take 
                , 
                    "Take must not be less than one" 
                ) ) ;
            }

            if ( Take > Things.Count )
            {
                throw ( new System.ArgumentOutOfRangeException 
                ( 
                    "Take" 
                , 
                    Take 
                , 
                    "Take must not be greater than the number of items in Things" 
                ) ) ;
            }
            
            PIEBALD.Types.UniqueIntStack stack = 
                new PIEBALD.Types.UniqueIntStack() ;
        
            StackState state = StackState.Push ;

            stack.Push ( 0 ) ;
        
            while ( state != StackState.Break ) 
            {
                switch ( state )
                {
                    case StackState.Push :
                    {
                        if ( stack.Count == Take )
                        {
                            state = StackState.Return ;
                        }
                        else if ( stack.Push ( 0 ) == Things.Count )
                        {
                            state = StackState.Pop ;
                        }

                        break ;
                    }

                    case StackState.Pop :
                    {
                        stack.Pop() ;

                        if ( stack.Count == 0 )
                        {
                            state = StackState.Break ;
                        }
                        else
                        {
                            state = StackState.Increment ;
                        }

                        break ;
                    }

                    case StackState.Increment :
                    {
                        if ( stack.Push ( stack.Pop() + 1 ) == Things.Count )
                        {
                            state = StackState.Pop ;
                        }
                        else
                        {
                            state = StackState.Push ;
                        }

                        break ;
                    }

                    case StackState.Return :
                    {
                        yield return ( Things.ApplyIndices ( stack.Values ) ) ;

                        state = StackState.Increment ;

                        break ;
                    }
                }
            }
        
            yield break ;
        }

        private enum StackState
        {
            Push
        ,
            Pop
        ,
            Increment
        ,
            Return
        ,
            Break
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
BSCS 1992 Wentworth Institute of Technology

Originally from the Boston (MA) area. Lived in SoCal for a while. Now in the Phoenix (AZ) area.

OpenVMS enthusiast, ISO 8601 evangelist, photographer, opinionated SOB, acknowledged pedant and contrarian

---------------

"I would be looking for better tekkies, too. Yours are broken." -- Paul Pedant

"Using fewer technologies is better than using more." -- Rico Mariani

"Good code is its own best documentation. As you’re about to add a comment, ask yourself, ‘How can I improve the code so that this comment isn’t needed?’" -- Steve McConnell

"Every time you write a comment, you should grimace and feel the failure of your ability of expression." -- Unknown

"If you need help knowing what to think, let me know and I'll tell you." -- Jeffrey Snover [MSFT]

"Typing is no substitute for thinking." -- R.W. Hamming

"I find it appalling that you can become a programmer with less training than it takes to become a plumber." -- Bjarne Stroustrup

ZagNut’s Law: Arrogance is inversely proportional to ability.

"Well blow me sideways with a plastic marionette. I've just learned something new - and if I could award you a 100 for that post I would. Way to go you keyboard lovegod you." -- Pete O'Hanlon

"linq'ish" sounds like "inept" in German -- Andreas Gieriet

"Things would be different if I ran the zoo." -- Dr. Seuss

"Wrong is evil, and it must be defeated." –- Jeff Ello

"A good designer must rely on experience, on precise, logical thinking, and on pedantic exactness." -- Nigel Shaw

“It’s always easier to do it the hard way.” -- Blackhart

“If Unix wasn’t so bad that you can’t give it away, Bill Gates would never have succeeded in selling Windows.” -- Blackhart

"Use vertical and horizontal whitespace generously. Generally, all binary operators except '.' and '->' should be separated from their operands by blanks."

"Omit needless local variables." -- Strunk... had he taught programming

Comments and Discussions