예제 #1
0
        public static IEnumerable <uint> Permutations(uint value, int numBits)
        {
            uint baseTerm      = Bit.GetFirst(value, numBits);
            uint mask          = Bit.GetRange(value, numBits, numBits);
            uint variant       = 0;
            int  variantLength = Bit.OnesCount(mask);

            if (variantLength == 0)
            {
                yield return(baseTerm);

                yield break;
            }

            uint maxVariant = Bit.MaxNum(variantLength);

            for (; variant <= maxVariant; variant++)
            {
                uint variantOne     = 1;
                uint lastVariantOne = 1u << variantLength;
                uint maskOne        = 1;
                uint permutation    = baseTerm;
                do
                {
                    if ((mask & maskOne) != 0)
                    {
                        if ((variant & variantOne) == 0)
                        {
                            permutation &= ~maskOne;
                        }
                        else
                        {
                            permutation |= maskOne;
                        }

                        variantOne <<= 1;
                    }

                    maskOne <<= 1;
                } while (variantOne < lastVariantOne);

                yield return(permutation);
            }
        }