using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace HeuristicLab.Problems.GrammaticalOptimization { // 4-bit even parity public class EvenParityProblem : IProblem { // + == OR // * == AND private const string grammarString = @" G(S): S -> N | N*S | N+S | !S | (S) N -> a | b | c | d "; private readonly IGrammar grammar; private readonly ExpressionInterpreter interpreter = new ExpressionInterpreter(); public EvenParityProblem() { this.grammar = new Grammar (grammarString); } public double BestKnownQuality(int maxLen) { // for now only an upper bound is returned, ideally all fitness cases are predicted correctly return Math.Pow(2, 4); } public IGrammar Grammar { get { return grammar; } } public double Evaluate(string sentence) { var vars = new bool[4]; var nCorrect = 0; for (int b0 = 0; b0 <= 1; b0++) for (int b1 = 0; b1 <= 1; b1++) for (int b2 = 0; b2 <= 1; b2++) for (int b3 = 0; b3 <= 1; b3++) { vars[0] = b0 > 0; vars[1] = b1 > 0; vars[2] = b2 > 0; vars[3] = b3 > 0; var pred = interpreter.Interpret(sentence, vars); var target = (b0 > 0) ^ (b1 > 0) ^ (b2 > 0) ^ (b3 > 0); if (pred == target) nCorrect++; } return nCorrect; } public string CanonicalRepresentation(string terminalPhrase) { return terminalPhrase; } } }