Click here to Skip to main content
15,885,278 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.8K   365   16  
Enumerating permutations and combinations without recursion.

# region Heading

/**************************************************************************************************************/
/*                                                                                                            */
/*  UniqueInt.cs                                                                                              */
/*                                                                                                            */
/*  Implements a class to hold an int with a unique value.                                                    */
/*                                                                                                            */
/*  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.Types
{
    /**
    <summary>
        Implements a class to hold an int with a unique value.
    </summary>
    <remarks>
        Uses a System.Collections.Generic.HashSet&lt;int&gt; to keep track of used values.
    </remarks>
    */
    public sealed class UniqueInt : System.IDisposable
    {
        private System.Collections.Generic.HashSet<int> taken ;

        private readonly int current ;
        
        /**
        <summary>
            Instantiates a new UniqueInt.
        </summary>
        <param name="Value">
            The initial value to try.
            If the provided value is in use, the value will be incremented until an unused value is reached.
        </param>
        <param name="Taken">
            The HashSet to use for checking uniqueness.
        </param>
        <exception cref="System.ArgumentNullException">
            If Taken is null.
        </exception>
        */
        public UniqueInt
        (
            int                                     Value
        ,
            System.Collections.Generic.HashSet<int> Taken
        )
        {
            if ( Taken == null )
            {
                throw ( new System.ArgumentNullException
                (
                    "Taken"
                ,
                    "Taken must not be null"
                ) ) ;
            }
        
            this.taken = Taken ;
            
            lock ( this.taken )
            {
                while ( this.taken.Contains ( Value ) )
                {
                    Value++ ;
                }

                this.taken.Add ( this.current = Value ) ;
            }
            
            return ;
        } 
        
        /**
        <summary>
            Removes the value from the HashSet and releases the HashSet.
        </summary>
        */
        public void
        Dispose
        (
        )
        {
            if ( this.taken != null )
            {
                this.taken.Remove ( this.current ) ;
                
                this.taken = null ;
            }                    

            return ;
        }

        /**
        <summary>
            Accesses the value.
        </summary>
        <value>
            The value of the encapsulated int.
        </value>
        <exception cref="System.ObjectDisposedException">
            If the instance has been disposed.
        </exception>
        */
        public int
        Value
        {
            get
            {
                if ( this.taken == null )
                {
                    throw ( new System.ObjectDisposedException
                        ( "" , "This instance has been disposed" ) ) ;
                }

                return ( this.current ) ;
            }
        }
        
        /**
        <summary>
            The Value as a string.
        </summary>
        <returns>
            The Value as a string.
        </returns>
        <exception cref="System.ObjectDisposedException">
            If the instance has been disposed.
        </exception>
        */
        public override string
        ToString
        (
        )
        {
            return ( this.Value.ToString() ) ;
        }
        
        /**
        <summary>
            This is an implicit conversion operator from UniqueInt to int.
        </summary>
        <returns>
            The Value.
        </returns>
        <exception cref="System.ObjectDisposedException">
            If the instance has been disposed.
        </exception>
        */
        public static implicit operator 
        int 
        ( 
            UniqueInt Op 
        )
        {
            return ( Op.Value ) ;
        }
    }

    /**
    <summary>
        Implements a class to make working with UniqueInts a little easier.
    </summary>
    <remarks>
        All int values from a particular factory will be unique.
    </remarks>
    */
    public sealed class UniqueIntFactory
    {
        private readonly System.Collections.Generic.HashSet<int> taken ;
            
        /**
        <summary>
            Instantiate a HashSet and wrap it in a UniqueIntFactory.
        </summary>
        */
        public UniqueIntFactory
        (
        )
        {
            this.taken = new System.Collections.Generic.HashSet<int>() ;
            
            return ;
        }
        
        /**
        <summary>
            Instantiate a new UniqueInt with this factory's HashSet and an initial value of zero (0).
        </summary>
        */
        public UniqueInt
        NewValue
        (
        )
        {
            return ( new UniqueInt ( 0 , this.taken ) ) ;
        }

        /**
        <summary>
            Instantiate a new UniqueInt with this factory's HashSet.
        </summary>
        <param name="Value">
            The initial value for the new UniqueInt.
        </param>
        */
        public UniqueInt
        NewValue
        (
            int Value
        )
        {
            return ( new UniqueInt ( Value , this.taken ) ) ;
        }
    } 
}

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