Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Problems.GrammaticalOptimization/EvenParityProblem.cs @ 11732

Last change on this file since 11732 was 11732, checked in by gkronber, 9 years ago

#2283: refactoring and bug fixes

File size: 1.6 KB
RevLine 
[11659]1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.Linq;
5using System.Text;
6using System.Text.RegularExpressions;
7
8namespace HeuristicLab.Problems.GrammaticalOptimization {
9  // 4-bit even parity
10  public class EvenParityProblem : IProblem {
11    // + == OR
12    // * == AND
13    private const string grammarString = @"
14G(S):
15S -> N | N*S | N+S | !S | (S)
16N -> a | b | c | d
17";
18
19    private readonly IGrammar grammar;
20    private readonly ExpressionInterpreter interpreter = new ExpressionInterpreter();
21    public EvenParityProblem() {
[11732]22      this.grammar = new Grammar (grammarString);
[11659]23    }
24
[11732]25    public double BestKnownQuality(int maxLen) {
[11659]26      // for now only an upper bound is returned, ideally all fitness cases are predicted correctly
27      return Math.Pow(2, 4);
28    }
29
30    public IGrammar Grammar {
31      get { return grammar; }
32    }
33
34    public double Evaluate(string sentence) {
35      var vars = new bool[4];
36      var nCorrect = 0;
37      for (int b0 = 0; b0 <= 1; b0++)
38        for (int b1 = 0; b1 <= 1; b1++)
39          for (int b2 = 0; b2 <= 1; b2++)
40            for (int b3 = 0; b3 <= 1; b3++) {
41              vars[0] = b0 > 0;
42              vars[1] = b1 > 0;
43              vars[2] = b2 > 0;
44              vars[3] = b3 > 0;
45
46              var pred = interpreter.Interpret(sentence, vars);
47              var target = (b0 > 0) ^ (b1 > 0) ^ (b2 > 0) ^ (b3 > 0);
48              if (pred == target) nCorrect++;
49            }
50      return nCorrect;
51    }
[11727]52
53    public string Hash(string terminalPhrase) {
54      return terminalPhrase;
55    }
[11659]56  }
57}
Note: See TracBrowser for help on using the repository browser.