static void Main(string[] args)
        {
            uint[]           outputIntegers = KaterynaBodnarchukTask.KateBodnarchukCase;
            bool[]           output         = BitTools.GetOutputBool(outputIntegers);
            List <Implicant> constituents   = PositiveMcCluskeyMethod.GetConstituents(output);
            string           constituentsDisjunctionFormString =
                Implicant.GetDisjunctionFormString(constituents);

            Console.WriteLine("Original Function: " + constituentsDisjunctionFormString);

            var minimalDisjunctionalNormalFunction =
                PositiveMcCluskeyMethod.GetImplicantDisjunctionNormalForm(output);

            Console.WriteLine(
                "Optimized Function: "
                +
                Implicant.GetDisjunctionFormString(minimalDisjunctionalNormalFunction)
                );

            uint input = uint.Parse(Console.ReadLine());

            Console.WriteLine(
                "Output: "
                +
                ImplicantDisjunctionNormalForm.Evaluate(
                    minimalDisjunctionalNormalFunction,
                    input
                    )
                );
            Console.ReadKey();
        }
Esempio n. 2
0
        public void quineTest()
        {
            //int[] minterms1 = new int[10] {0, 1, 2, 5, 6, 7, 8, 9, 10, 14};
            int[] minterms1                = new int[] { 0, 1, 2, 5, 6, 7 };
            BooleanAlgebra.Quine quine1    = new BooleanAlgebra.Quine(minterms1, 3);
            List <Implicant>     essential = quine1.simplify();

            System.Console.WriteLine(quine1.ToString());

            Console.WriteLine("The Expression is");
            Console.WriteLine(Implicant.ConvertToExpression(essential));
        }
        internal static Implicant <T> CombineImplicants <T>(
            this Implicant <T> implicantA,
            Implicant <T> implicantB)
        {
            var variableTermMapB = implicantB
                                   .TermSet
                                   .ToDictionary(
                keySelector: term => term.Value,
                elementSelector: term => term);

            var combinedMinterm = implicantA
                                  .TermSet
                                  .Select(termA =>
            {
                var variable = termA.Value;
                var termB    = variableTermMapB[variable];
                return((termA, termB) switch
                {
                    (PositiveTerm <T> _, NegativeTerm <T> _) => new CombinedTerm <T>(variable),
                    (NegativeTerm <T> _, PositiveTerm <T> _) => new CombinedTerm <T>(variable),
                    _ => termA
                });
            })
 public ReducedBooleanExpression(ExpandedBooleanExpression bexpr)
 {
     _sortedVariables = bexpr.GetAllVariables();
     ushort index = 0;
     foreach (char c in _sortedVariables)
     {
         _alphabet[c] = index;
         index++;
     }
     Implicant i = null;
     foreach (string factor in bexpr.AsString.Split('+'))
     {
         i = new Implicant(this, factor);
         if ((i == null) || (i.IsContradiction))
             continue;
         _implicants.Add(i);
     }
     //
     CalculatePrimeImplicants();
     BuildMintermToPrimeImplicantTable();
     _mintermCount = _primeImplicantTable.Count();
     PickFinalImplicants();
 }
Esempio n. 5
0
        public static string GetSimplified(IEnumerable <LogicItem> List, int variables, bool hazardsafe = false, bool lsba = false, bool negate = false)
        {
            var implicants = new ImplicantCollection();

            var items        = (from i in List where i.Checked == true || i.Checked == null orderby i.Index ascending select i.Index).ToArray();
            var careminterms = (from i in List where i.Checked == true orderby i.Index ascending select i.Index).ToArray();



            foreach (var item in items)
            {
                var m = new Implicant();
                m.Mask = LogicItem.GetBinaryValue(item, variables);
                m.Minterms.Add(item);
                implicants.Add(m);
            }

            //int count = 0;
            while (Simplify(ref implicants))
            {
                //Populate a matrix.
                bool[,] matrix = new bool[implicants.Count, items.Length]; //x, y
                PopulateMatrix(ref matrix, implicants, items);
            }
            ImplicantCollection selected;

            if (hazardsafe)
            {
                selected = implicants;
            }
            else
            {
                selected = SelectImplicants(implicants, careminterms);
            }
            return(GetFinalExpression(selected, lsba, negate));
        }
Esempio n. 6
0
 public ImplicantRelationship(Implicant first, Implicant second)
 {
     A = first;
     B = second;
 }
        /*
         * Entry point.
         */
        public static void Main(string[] args)
        {
            int[] input = null;

            Console.WriteLine("Michael Landi\t\tComp. Architecture.");
            Console.WriteLine("Boolean Simplification Program");
            Console.WriteLine();
            Console.Write("ENTER MINTERMS: ");
            string[] minterms = Console.ReadLine().Split(' ');
            Console.WriteLine();

            //Parse and validate input.
            try
            {
                input = new int[minterms.Length];
                for (int i = 0; i < input.Length; i++)
                {
                    input[i] = -1; //That way we can check for duplicate zeroes.
                }
                //Empty string passed.
                if (minterms.Length == 0 || minterms[0].Trim() == string.Empty)
                {
                    throw new Exception("No input.");
                }

                for (int i = 0; i < minterms.Length; i++)
                {
                    int check = Int32.Parse(minterms[i]);

                    if (check < 0)
                    {
                        throw new Exception("Input cannot be less than zero.");
                    }
                    if (input.Contains(check))
                    {
                        throw new Exception("Input cannot contain the same minterm twice.");
                    }

                    input[i] = check;
                }
                Array.Sort(input);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: " + ex.Message);
                Environment.Exit(-1);
            }

            //Create initial list of  minterms.
            ImplicantCollection implicants = new ImplicantCollection();

            foreach (int i in input)
            {
                Implicant m = new Implicant();
                m.Mask = Convert.ToString(i, 2);
                m.Minterms.Add(i);
                implicants.Add(m);
            }

            //Simplify expressions.
            int count = 0;

            while (Simplify(ref implicants))
            {
                //Populate a matrix.
                bool[,] matrix = new bool[implicants.Count, input.Length]; //x, y
                PopulateMatrix(ref matrix, implicants, input);
                PrintMatrix(matrix, input, ++count);
            }

            //Select implicants.
            ImplicantCollection selected = SelectImplicants(implicants, input);
            string strFinal = GetFinalExpression(selected);

            Console.WriteLine();
            Console.WriteLine("SIMPLIFIED EXPRESSION: ");
            Console.WriteLine(strFinal);
            Console.ReadKey();
        }
        /*
         * Simplifies a givenset of implicants.
         */
        private static bool Simplify(ref ImplicantCollection implicants)
        {
            /*
             * Group by number of 1's and determine relationships by comparing.
             */
            ImplicantGroup group = Group(implicants);
            ImplicantRelationshipCollection relationships = new ImplicantRelationshipCollection();

            for (int i = 0; i < group.Keys.Count; i++)
            {
                if (i == (group.Keys.Count - 1))
                {
                    break;
                }

                ImplicantCollection thisGroup = group[group.Keys.ElementAt(i)];
                ImplicantCollection nextGroup = group[group.Keys.ElementAt(i + 1)];

                foreach (Implicant a in thisGroup)
                {
                    foreach (Implicant b in nextGroup)
                    {
                        if (GetDifferences(a.Mask, b.Mask) == 1)
                        {
                            relationships.Add(new ImplicantRelationship(a, b));
                        }
                    }
                }
            }

            /*
             * For each relationship, find the affected minterms and remove them.
             * Then add a new implicant which simplifies the affected minterms.
             */
            foreach (ImplicantRelationship r in relationships)
            {
                ImplicantCollection rmList = new ImplicantCollection();

                foreach (Implicant m in implicants)
                {
                    if (r.a.Equals(m) || r.b.Equals(m))
                    {
                        rmList.Add(m);
                    }
                }

                foreach (Implicant m in rmList)
                {
                    implicants.Remove(m);
                }

                Implicant newImplicant = new Implicant();
                newImplicant.Mask = GetMask(r.a.Mask, r.b.Mask);
                newImplicant.Minterms.AddRange(r.a.Minterms);
                newImplicant.Minterms.AddRange(r.b.Minterms);

                bool exist = false;
                foreach (Implicant m in implicants)
                {
                    if (m.Mask == newImplicant.Mask)
                    {
                        exist = true;
                    }
                }

                if (!exist) //Why am I getting dupes?
                {
                    implicants.Add(newImplicant);
                }
            }

            //Return true if simplification occurred, false otherwise.
            return(!(relationships.Count == 0));
        }
Esempio n. 9
0
        /*
         * Simplifies a givenset of implicants.
         */
        private static bool Simplify(ref ImplicantCollection implicants)
        {
            /*
             * Group by number of 1's and determine relationships by comparing.
             */
            var groups        = (from i in Group(implicants) orderby i.Key select i).ToDictionary(i => i.Key, i => i.Value);
            var relationships = new ImplicantRelationshipCollection();

            for (int i = 0; i < groups.Keys.Count; i++)
            {
                if (i == (groups.Keys.Count - 1))
                {
                    break;
                }

                var thisGroup = groups[groups.Keys.ElementAt(i)];
                var nextGroup = groups[groups.Keys.ElementAt(i + 1)];

                var q = from a in thisGroup from b in nextGroup where GetDifferences(a.Mask, b.Mask) == 1 select new ImplicantRelationship(a, b);
                relationships.AddRange(q);
            }

            /*
             * For each relationship, find the affected minterms and remove them.
             * Then add a new implicant which simplifies the affected minterms.
             */
            foreach (ImplicantRelationship r in relationships)
            {
                var rmList = new ImplicantCollection();

                foreach (Implicant m in implicants)
                {
                    if (r.a.Equals(m) || r.b.Equals(m))
                    {
                        rmList.Add(m);
                    }
                }

                foreach (Implicant m in rmList)
                {
                    implicants.Remove(m);
                }

                var newImplicant = new Implicant();
                newImplicant.Mask = GetMask(r.a.Mask, r.b.Mask);
                newImplicant.Minterms.AddRange(r.a.Minterms);
                newImplicant.Minterms.AddRange(r.b.Minterms);

                bool exist = false;
                foreach (Implicant m in implicants)
                {
                    if (m.Mask == newImplicant.Mask)
                    {
                        exist = true;
                    }
                }

                if (!exist) //Why am I getting dupes?
                {
                    implicants.Add(newImplicant);
                }
            }

            //Return true if simplification occurred, false otherwise.
            return(!(relationships.Count == 0));
        }
Esempio n. 10
0
        public static Expr QuineMcCluskey(Expr e, IEnumerable <Expr> knownTrue)
        {
            HashSet <Expr> variables = new HashSet <Expr>();
            Action <Expr>  findVars  = null;

            findVars = x => {
                bool isVar = true;
                switch (x.ExprType)
                {
                case Expr.NodeType.Unary:
                    var eUnary = (ExprUnary)x;
                    if (eUnary.Op == UnaryOp.Not)
                    {
                        findVars(eUnary.Expr);
                        isVar = false;
                    }
                    break;

                case Expr.NodeType.Binary:
                    var eBinary = (ExprBinary)x;
                    if (eBinary.Op == BinaryOp.And || eBinary.Op == BinaryOp.Or)
                    {
                        findVars(eBinary.Left);
                        findVars(eBinary.Right);
                        isVar = false;
                    }
                    break;

                case Expr.NodeType.Literal:
                    isVar = false;
                    break;
                }
                if (isVar)
                {
                    variables.Add(x);
                }
            };
            findVars(e);

            var useKnownTrue = knownTrue.Where(x => GetVarsVisitor.GetAll(x).All(y => variables.Contains(y))).ToArray();
            var exprs        = variables.ToArray();
            var exprMap      = exprs.Select((x, i) => new { x, i }).ToDictionary(x => x.x, x => x.i);

            var truthTable = EnumBits(exprs)
                             .Select(bits => {
                foreach (var known in useKnownTrue)
                {
                    var knownResult = EvalVisitor.Eval(bits, exprMap, known);
                    if (!knownResult)
                    {
                        return(null);
                    }
                }
                return((bool?)EvalVisitor.Eval(bits, exprMap, e));
            })
                             .ToArray();

            var nextStageImplicants = new HashSet <Implicant>(truthTable
                                                              .Select((x, i) => new { bits = new Bits(i), x })
                                                              .Where(x => !x.x.HasValue || x.x.Value)
                                                              .Select(x => new Implicant(x.bits, 0, new[] { x.bits.Value })), Implicant.EqComparerInstance);

            var primeImplicants = new List <Implicant>();

            while (nextStageImplicants.Any())
            {
                var minTerms = nextStageImplicants
                               .GroupBy(x => x.Bits.BitCount)
                               .OrderBy(x => x.Key)
                               .ToArray();
                nextStageImplicants.Clear();
                Implicant[] sameBitCount1 = minTerms[0].OrderBy(x => x.DoesntMatter).ThenBy(x => x.Bits.Value).ToArray(), sameBitCount0 = null;
                for (var sameBitCountIdx = 1; sameBitCountIdx < minTerms.Length; sameBitCountIdx++)
                {
                    sameBitCount0 = sameBitCount1;
                    sameBitCount1 = minTerms[sameBitCountIdx].OrderBy(x => x.DoesntMatter).ThenBy(x => x.Bits.Value).ToArray();
                    for (int i = 0; i < sameBitCount0.Length; i++)
                    {
                        for (int j = 0; j < sameBitCount1.Length; j++)
                        {
                            var minTerm0 = sameBitCount0[i];
                            var minTerm1 = sameBitCount1[j];
                            if (minTerm0.DoesntMatter == minTerm1.DoesntMatter)
                            {
                                var diff = new Bits(minTerm0.Bits.Value ^ minTerm1.Bits.Value);
                                if (diff.BitCount == 1)
                                {
                                    var combinedBits         = minTerm0.Bits.Value & minTerm1.Bits.Value;
                                    var combinedDoesntMatter = minTerm0.DoesntMatter | diff.Value;
                                    var combinedCovers       = minTerm0.Covers.Concat(minTerm1.Covers).OrderBy(x => x).ToArray();
                                    var combined             = new Implicant(new Bits(combinedBits), combinedDoesntMatter, combinedCovers);
                                    nextStageImplicants.Add(combined);
                                    sameBitCount0[i].Combined = true;
                                    sameBitCount1[j].Combined = true;
                                }
                            }
                        }
                    }
                    primeImplicants.AddRange(sameBitCount0.Where(x => !x.Combined));
                }
                primeImplicants.AddRange(sameBitCount1.Where(x => !x.Combined));
            }

            primeImplicants = primeImplicants.OrderBy(x => x.Bits.Value).ThenBy(x => x.DoesntMatter).ToList();

            var requiredMinTerms = truthTable
                                   .Select((x, i) => new { x, i })
                                   .Where(x => x.x.HasValue && x.x.Value)
                                   .Select(x => x.i)
                                   .ToArray();

            var essentialPrimeImplicants = new HashSet <Implicant>();

            for (int i = 0; i < requiredMinTerms.Length; i++)
            {
                var requiredMinTerm = requiredMinTerms[i];
                var covers          = primeImplicants.Where(x => x.Covers.Contains(requiredMinTerm)).ToArray();
                if (covers.Length == 1)
                {
                    essentialPrimeImplicants.Add(covers[0]);
                }
            }

            var requiredPrimeImplicants = essentialPrimeImplicants.ToArray();

            var nonEssentialMinTerms        = requiredMinTerms.Where(x => !essentialPrimeImplicants.Any(y => y.Covers.Contains(x))).ToArray();
            var nonEssentialPrimeImplicants = primeImplicants.Except(essentialPrimeImplicants).ToArray();

            if (nonEssentialMinTerms.Any() && nonEssentialPrimeImplicants.Any())
            {
                var extraPrimeImplicants = FindOptimalImplicants(nonEssentialPrimeImplicants, nonEssentialMinTerms);
                requiredPrimeImplicants = requiredPrimeImplicants.Concat(extraPrimeImplicants).ToArray();
            }

            var  ctx = e.Ctx;
            Expr eResult;

            if (!requiredPrimeImplicants.Any())
            {
                eResult = ctx.Literal(false);
            }
            else
            {
                var requiredAndExprs = requiredPrimeImplicants
                                       .Select(x => {
                    var toOr = Enumerable.Range(0, exprs.Length).Select(i => {
                        var mask = 1 << i;
                        if ((x.DoesntMatter & mask) != 0)
                        {
                            return(null);
                        }
                        var needNot = (x.Bits.Value & mask) == 0;
                        if (needNot)
                        {
                            return(ctx.ExprGen.Not(exprs[i]));
                        }
                        else
                        {
                            return(exprs[i]);
                        }
                    })
                               .Where(y => y != null)
                               .ToArray();
                    if (toOr.Any())
                    {
                        var orExpr = toOr.Aggregate((a, b) => ctx.ExprGen.And(a, b));
                        return(orExpr);
                    }
                    else
                    {
                        return(ctx.Literal(true));
                    }
                })
                                       .ToArray();
                eResult = requiredAndExprs.Aggregate((a, b) => ctx.ExprGen.Or(a, b));
            }

            if (e.DoesEqual(eResult))
            {
                return(e);
            }
            else
            {
                return(eResult);
            }
        }
Esempio n. 11
0
 private static AndFunction ToAndFunciton(Implicant implicant)
 => new AndFunction(
     implicant.Items.Select(GetInputSignFunction));